问:
cookies not being deleted
I have a basic login system. The basic login / logout functions are as follows:

```<code>function login() {
    global $page;

    if ($_COOKIE['adminUser'] == adminUser && $_COOKIE['adminPass'] == adminPass):
        $_SESSION['adminLogin'] = true;
        redirect($_SERVER['REQUEST_URI']);
    elseif ($_POST['adminUser'] == adminUser && $_POST['adminPass'] == adminPass):
        setcookie('adminUser', $_POST['adminUser'], time() + 60 * 60 * 24 * 7);
        setcookie('adminPass', $_POST['adminPass'], time() + 60 * 60 * 24 * 7);
        $_SESSION['adminLogin'] = true;
        redirect($_SERVER['REQUEST_URI']);
    else:
        $page->content->table = new template('admin/login.tpl');
        // it shows the login form
    endif;
}

    function logout() {
        $_SESSION['adminLogin'] = false;
        setcookie('adminUser', false, time() - 60*100000);
        setcookie('adminPass', false, time() - 60*100000);
        redirect(pathApp);
    }
</code>```

redirect($x) is header("Location: $x"); die;.

No other COOKIES are being set anywhere in the entire script.

The problem is that the logout function is not working. I tried to debug this via Firebug, to see what headers are being sent and all seems ok to me. Here is Firebug's log for logout:

```<code>Response Headers

HTTP/1.1 200 OK
Date: Fri, 15 Apr 2011 18:48:57 GMT
Server: Apache
X-Powered-By: PHP/5.2.13
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Set-Cookie: adminUser=deleted; expires=Thu, 15-Apr-2010 18:48:56 GMT
adminPass=deleted; expires=Thu, 15-Apr-2010 18:48:56 GMT
Content-Length: 1041
Connection: close
Content-Type: text/html

Request Headers

GET /freeads/admin/logout HTTP/1.1
Host: clienti.bsorin.ro
User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.15) Gecko/20110303 Firefox/3.6.15
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Referer: http://clienti.bsorin.ro/freeads/admin
Cookie: adminUser=q; adminPass=q; PHPSESSID=22faf6e20467b88d97dc7838572cbd47
</code>```

The script is live at http://clienti.bsorin.ro/freeads/admin. Username and password are both set to 'q'.

Thanks!

答:
I noticed that you are using a sub-domain. setCookie has a fifth parameter that will specify the domain. It is tricky with sub-domains to delete cookies. This worked for me

```<code>setCookie("clockInTime", $param, date('U')+86502,'/', '.mywebsite.com')
</code>```

The last param will pick up any and all sub-domains of mywebsite using the '.' before the domain.

Title: cookies not being deleted

Body:
I have a basic login system. The basic login / logout functions are as follows:

function login() {
    global $page;

    if ($_COOKIE['adminUser'] == adminUser && $_COOKIE['adminPass'] == adminPass):
        $_SESSION['adminLogin'] = true;
        redirect($_SERVER['REQUEST_URI']);
    elseif ($_POST['adminUser'] == adminUser && $_POST['adminPass'] == adminPass):
        setcookie('adminUser', $_POST['adminUser'], time() + 60 * 60 * 24 * 7);
        setcookie('adminPass', $_POST['adminPass'], time() + 60 * 60 * 24 * 7);
        $_SESSION['adminLogin'] = true;
        redirect($_SERVER['REQUEST_URI']);
    else:
        $page->content->table = new template('admin/login.tpl');
        // it shows the login form
    endif;
}

    function logout() {
        $_SESSION['adminLogin'] = false;
        setcookie('adminUser', false, time() - 60*100000);
        setcookie('adminPass', false, time() - 60*100000);
        redirect(pathApp);
    }

redirect($x) is header("Location: $x"); die;.

No other COOKIES are being set anywhere in the entire script.

The problem is that the logout function is not working. I tried to debug this via Firebug, to see what headers are being sent and all seems ok to me. Here is Firebug's log for logout:

Response Headers

HTTP/1.1 200 OK
Date: Fri, 15 Apr 2011 18:48:57 GMT
Server: Apache
X-Powered-By: PHP/5.2.13
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Set-Cookie: adminUser=deleted; expires=Thu, 15-Apr-2010 18:48:56 GMT
adminPass=deleted; expires=Thu, 15-Apr-2010 18:48:56 GMT
Content-Length: 1041
Connection: close
Content-Type: text/html

Request Headers

GET /freeads/admin/logout HTTP/1.1
Host: clienti.bsorin.ro
User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.15) Gecko/20110303 Firefox/3.6.15
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Referer: http://clienti.bsorin.ro/freeads/admin
Cookie: adminUser=q; adminPass=q; PHPSESSID=22faf6e20467b88d97dc7838572cbd47

The script is live at http://clienti.bsorin.ro/freeads/admin. Username and password are both set to 'q'.

Thanks!

Body:
I noticed that you are using a sub-domain. setCookie has a fifth parameter that will specify the domain. It is tricky with sub-domains to delete cookies. This worked for me

setCookie("clockInTime", $param, date('U')+86502,'/', '.mywebsite.com')

The last param will pick up any and all sub-domains of mywebsite using the '.' before the domain.


来源: stackexchange

问:
Vue 2 - Styling HTML returned in a switch statement
I'm building a generic component supposed to receive various backend data. I wrote a switch. One condition is :

```<code>case 'Bases':
                let bases = variant[tableName][colValue].map((base) => {
                    return `<div class="base b${base.strongestIndication}">${base.name}</div>`
                })
                return bases.join('')
</code>```

I use v-html in my template, therefore in this case, we have 3 divs created, each with a class of "base" and then "b1", "b2", "b3". I can see on the webpage that these classes are properly set when I inspect the elements.

I've described in my style some rules for theses classes (mostly background-color, border-radius and so on), but they do not apply.

I'm guessing this might have something to do with the CSS being applied before these divs are created but I'm not sure of this.

What should I do to get these tags created by JS to be styled properly ?

(Also, I know using v-html can be dangerous, therefore if you have a better idea for this whole thing, I'm all ears)

答: Figured it out. For those wondering, switch statements returning html code aren't styled if the  tag in your file is scoped. Unsure why, but removing scoped work. If you decide to do so, but unique class names, as these styles will spread all throughout the application !</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm building a generic component supposed to receive various backend data. I wrote a switch. One condition is :

case 'Bases':
                let bases = variant[tableName][colValue].map((base) => {
                    return `<div class="base b${base.strongestIndication}">${base.name}</div>`
                })
                return bases.join('')

I use v-html in my template, therefore in this case, we have 3 divs created, each with a class of "base" and then "b1", "b2", "b3". I can see on the webpage that these classes are properly set when I inspect the elements.

I've described in my style some rules for theses classes (mostly background-color, border-radius and so on), but they do not apply.

I'm guessing this might have something to do with the CSS being applied before these divs are created but I'm not sure of this.

What should I do to get these tags created by JS to be styled properly ?

(Also, I know using v-html can be dangerous, therefore if you have a better idea for this whole thing, I'm all ears)


问:
How to download files which are created in last 24 hours using gsutil in GCP console?
I have a directory in a gcp storage bucket. And there are 2 subdirectories in that bucket.

Is there a way to download files which are created in last 24 hours in those subdirectories using gsutil command from console?

答:
I was able to achieve part of it using gcp console and shell.

Steps:

Go to storage directory in browser gcp console.

Click on filter and you'll get options to filter based on created before, created after etc.

Provide the date and apply filter

Click on Download button

Copy the command, Open the gcp shell and run it. The required files will be downloaded there.

Run the zip command in shell and archive the downloaded files.

Select the Download from shell options and provide file path to download.


问:
Unable to get table output with stargazer in Rmarkdown
I tried to present my regression table on R markdown and I had even added the results='asis' to the R code chunk but he final result is still the latex code from the stargazer output and not the table

```<code>```{r, results='asis'}
  stargazer(lm(mpg ~ wt, data=mtcars), header=FALSE)
```
</code>```

and my output was

```<code>\begin{table}[!htbp] \centering
  \caption{}
  \label{}
\begin{tabular}{@{\extracolsep{5pt}}lc}
\\[-1.8ex]\hline
\hline \\[-1.8ex]
 & \multicolumn{1}{c}{\textit{Dependent variable:}} \\
\cline{2-2}
\\[-1.8ex] & mpg \\
\hline \\[-1.8ex]
 wt & $-$5.344$^{***}$ \\
  & (0.559) \\
  & \\
 Constant & 37.285$^{***}$ \\
  & (1.878) \\
  & \\
\hline \\[-1.8ex]
Observations & 32 \\
R$^{2}$ & 0.753 \\
Adjusted R$^{2}$ & 0.745 \\
Residual Std. Error & 3.046 (df = 30) \\
F Statistic & 91.375$^{***}$ (df = 1; 30) \\
\hline
\hline \\[-1.8ex]
\textit{Note:}  & \multicolumn{1}{r}{$^{*}$p$<$0.1; $^{**}$p$<$0.05; $^{***}$p$<$0.01} \\
\end{tabular}
\end{table}
</code>```

which was the latex code. How do I fix this?

答:
Stargazer outputs latex by default. You can vary the output format by type.

From ?stargazer

```<code>type: a character vector that specifies what type of output the
      command should produce. The possible values are ‘"latex"’
      (default) for LaTeX code, ‘"html"’ for HTML/CSS code,
      ‘"text"’ for ASCII text output.
</code>```

```<code>>stargazer(lm(mpg ~ wt, data=mtcars), header=FALSE, type='text')

===============================================
                        Dependent variable:
                    ---------------------------
                                mpg
-----------------------------------------------
wt                           -5.344***
                              (0.559)

Constant                     37.285***
                              (1.878)

-----------------------------------------------
Observations                    32
R2                             0.753
Adjusted R2                    0.745
Residual Std. Error       3.046 (df = 30)
F Statistic           91.375*** (df = 1; 30)
===============================================
Note:               *p<0.1; **p<0.05; ***p<0.01
</code>```

Body:
I tried to present my regression table on R markdown and I had even added the results='asis' to the R code chunk but he final result is still the latex code from the stargazer output and not the table

```{r, results='asis'}
  stargazer(lm(mpg ~ wt, data=mtcars), header=FALSE)
```

and my output was

\begin{table}[!htbp] \centering
  \caption{}
  \label{}
\begin{tabular}{@{\extracolsep{5pt}}lc}
\\[-1.8ex]\hline
\hline \\[-1.8ex]
 & \multicolumn{1}{c}{\textit{Dependent variable:}} \\
\cline{2-2}
\\[-1.8ex] & mpg \\
\hline \\[-1.8ex]
 wt & $-$5.344$^{***}$ \\
  & (0.559) \\
  & \\
 Constant & 37.285$^{***}$ \\
  & (1.878) \\
  & \\
\hline \\[-1.8ex]
Observations & 32 \\
R$^{2}$ & 0.753 \\
Adjusted R$^{2}$ & 0.745 \\
Residual Std. Error & 3.046 (df = 30) \\
F Statistic & 91.375$^{***}$ (df = 1; 30) \\
\hline
\hline \\[-1.8ex]
\textit{Note:}  & \multicolumn{1}{r}{$^{*}$p$<$0.1; $^{**}$p$<$0.05; $^{***}$p$<$0.01} \\
\end{tabular}
\end{table}

which was the latex code. How do I fix this?

Body:
Stargazer outputs latex by default. You can vary the output format by type.

From ?stargazer

type: a character vector that specifies what type of output the
      command should produce. The possible values are ‘"latex"’
      (default) for LaTeX code, ‘"html"’ for HTML/CSS code,
      ‘"text"’ for ASCII text output.

>stargazer(lm(mpg ~ wt, data=mtcars), header=FALSE, type='text')

===============================================
                        Dependent variable:
                    ---------------------------
                                mpg
-----------------------------------------------
wt                           -5.344***
                              (0.559)

Constant                     37.285***
                              (1.878)

-----------------------------------------------
Observations                    32
R2                             0.753
Adjusted R2                    0.745
Residual Std. Error       3.046 (df = 30)
F Statistic           91.375*** (df = 1; 30)
===============================================
Note:               *p<0.1; **p<0.05; ***p<0.01


问:
ASP.NET Core : create JWT token with invalid date
I'm trying to get an JWT token:

```<code>public async Task<string> GetAccessToken()
{
    var exp = await context.GetTokenAsync("expires_at");
    var expires = DateTime.Parse(exp);

    if (expires > DateTime.Now)
    {
        return await context.GetTokenAsync(OpenIdConnectParameterNames.AccessToken);
    }

    return await GetRefreshedAccessToken();
}
</code>```

But when I put the JWT string that was accepted in the token in https://token.dev/

I get invalid date on "auth_time" - why and how can I fix it?

答:
In JWT, the fields about time are in Unix Timestamp format.

You need to convert your time to this format.

```<code>[HttpGet("GetUnixTimeStamp")]
public string GetAccessToken()
{
    string dateStart = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:sszzz");
    DateTime Start = DateTime.ParseExact(dateStart, "yyyy-MM-ddTHH:mm:sszzz", System.Globalization.CultureInfo.InvariantCulture);

    long unixStart = (long)Start
        .ToUniversalTime()
        .Subtract(DateTime.UnixEpoch)
        .TotalSeconds;
    return unixStart.ToString();
}
</code>```

Body:
I'm trying to get an JWT token:

public async Task<string> GetAccessToken()
{
    var exp = await context.GetTokenAsync("expires_at");
    var expires = DateTime.Parse(exp);

    if (expires > DateTime.Now)
    {
        return await context.GetTokenAsync(OpenIdConnectParameterNames.AccessToken);
    }

    return await GetRefreshedAccessToken();
}

But when I put the JWT string that was accepted in the token in https://token.dev/

I get invalid date on "auth_time" - why and how can I fix it?

Body:
In JWT, the fields about time are in Unix Timestamp format.

You need to convert your time to this format.

[HttpGet("GetUnixTimeStamp")]
public string GetAccessToken()
{
    string dateStart = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:sszzz");
    DateTime Start = DateTime.ParseExact(dateStart, "yyyy-MM-ddTHH:mm:sszzz", System.Globalization.CultureInfo.InvariantCulture);

    long unixStart = (long)Start
        .ToUniversalTime()
        .Subtract(DateTime.UnixEpoch)
        .TotalSeconds;
    return unixStart.ToString();
}


问:
React limits the number of renders to prevent an infinite loop Error
Below is my code

```<code>function App() {
    const [isImportant, setIsImportant] = useState("Yes")

    function handleClick() {
        setIsImportant("No")
    }

    return (
        <div className="state">
            <h1 className="state--title">Is state important to know?</h1>
            <div className="state--value" onClick ={setIsImportant("No")} >
              {isImportant}
            </div>
        </div>
    )
}
</code>```

However I get the error which says 'Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.'

If someone can explain why the error is happening it would be grateful!!

答:
The onClick handler needs a function -- but what you pass is the result of calling setIsImportant("No"), thus setIsImportant("No") is called immediately when rendering.

To fix, pass a function instead. You actually already have one -- handleClick -- so use onClick={handleClick}.

Body:
Below is my code

function App() {
    const [isImportant, setIsImportant] = useState("Yes")

    function handleClick() {
        setIsImportant("No")
    }

    return (

Is state important to know?

              {isImportant}

    )
}

However I get the error which says 'Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.'

If someone can explain why the error is happening it would be grateful!!


问:
What does 0x80020101 represent?
A simple question that I can't find an answer for in Microsoft's error lookup or easily using google: what does the HRESULT 0x80020101 represent?</p>

答:
According to Eric Lippert in this blog post:

SCRIPT_E_REPORTED   0x80020101 -- the script engines return this
  to the host when there has been an unhandled error that the host has
  already been informed about via OnScriptError.

ContentLicense: CC BY-SA 3.0

Title: What does 0x80020101 represent?


问:
Not able the hide content in of HTML page and show it at the time of print
Hi I try to hide one of the chart from main page and want to show it at the time of print.But it is not working for me.

HTML:

```<code><div class="bar-chart">
  <div class="canvas-holder3"><canvas id="resultsChart7"></canvas></div>
</div>
</code>```

CSS:

```<code>.bar-chart {
  display: none;
}

@media print {
  body,
  html,
  #wrapper {
    width: 100%;
  }

  .bar-chart {
    display: block;
    visibility: visible;
  }
}
</code>```

答: you need to add javascript for that.</p>

Body:
Hi I try to hide one of the chart from main page and want to show it at the time of print.But it is not working for me.

HTML:

<canvas id="resultsChart7"></canvas>

CSS:

.bar-chart {
  display: none;
}

@media print {
  body,
  html,
  #wrapper {
    width: 100%;
  }

  .bar-chart {
    display: block;
    visibility: visible;
  }
}

Body: you need to add javascript for that.


问:
Replacing variable entries to be the same in each group
I'm working with panel data in Stata, and I have a set up like the following:

ID
year
value

1
2010

1
2011
20

1
2012
20

1
2013

1
2014

2
2010

2
2011
14

2
2012
14

2
2013
14

2
2014
14

and I want to change the blank entries to be the same as the other entries within that ID, for any year. I.e., I want something like the following:

ID
year
value

1
2010
20

1
2011
20

1
2012
20

1
2013
20

1
2014
20

2
2010
14

2
2011
14

2
2012
14

2
2013
14

2
2014
14

What do you recommend?

答:
If the value in variable value are always the same within id you can use this:

```<code>* Example generated by -dataex-. For more info, type help dataex
clear
input byte id int year byte value
1 2010  .
1 2011 20
1 2012 20
1 2013  .
1 2014  .
2 2010  .
2 2011 14
2 2012 14
2 2013 14
2 2014 14
end

*Get mean of values within id
bysort id : egen value2 = mean(value)

*Transfer values back to original var to maintain var labels etc. then drop value2
replace value = value2
drop value2
</code>```

Body:
If the value in variable value are always the same within id you can use this:

* Example generated by -dataex-. For more info, type help dataex
clear
input byte id int year byte value
1 2010  .
1 2011 20
1 2012 20
1 2013  .
1 2014  .
2 2010  .
2 2011 14
2 2012 14
2 2013 14
2 2014 14
end

*Get mean of values within id
bysort id : egen value2 = mean(value)

*Transfer values back to original var to maintain var labels etc. then drop value2
replace value = value2
drop value2


问:
how to bring the choose.file() dialog to the foreground
I'm using the function choose.dir() in a script that is run with rscript.exe under Windows XP. The problem is that the directory choosing dialog does not pop up as a top-level window. How can I bring the dialogue to the foreground?

In the meantime, I solved my problem by using visual basic script. Of course, this only works with windows:

```<code>tf <- tempfile(fileext = '.vbs')
cat('Set folder = CreateObject("Shell.Application") _
        .BrowseForFolder(0, "Please choose a folder" _
       , &H0001, 17)
       Wscript.Echo folder.Self.Path
', file = tf)
tail(shell(paste('Cscript', tf), intern = T), 1)
</code>```

答: After searching the rhelp archives it appears the answer is that you can't use choose.dir and file.choose in a non-interactive session. You might be able to do something similar, since list.files, file.info, file.access and files can be used to gather information, you can display this by writing to a graphics device and executing a system() call to get it displayed, and readLines can be used to get user input.

Body:
I'm using the function choose.dir() in a script that is run with rscript.exe under Windows XP. The problem is that the directory choosing dialog does not pop up as a top-level window. How can I bring the dialogue to the foreground?

In the meantime, I solved my problem by using visual basic script. Of course, this only works with windows:

tf <- tempfile(fileext = '.vbs')
cat('Set folder = CreateObject("Shell.Application") _
        .BrowseForFolder(0, "Please choose a folder" _
       , &H0001, 17)
       Wscript.Echo folder.Self.Path
', file = tf)
tail(shell(paste('Cscript', tf), intern = T), 1)


问:
Is there any way to extend Commerce Scale Unit customer and consumer APIs for Microsoft D365 Commerce?
Just now I have started learning Microsoft Dynamics 365 Commerce.
I have found an article that depicts the existing APIs.
Commerce Scale Unit customer and consumer APIs

Please correct me if I am wrong, Is there any way to extend these APIs to add some custom business logic?

I have gone through the docs provided by Microsoft but it is not mentioned anywhere how to extend the consumer APIs.

I have prefered this link Create a Retail Server extension API to create a new API but how to extend the existing one is not mentioned.

Any suggestion/response would be appreciated.

Thanks

答:
I have just figured out that We can extend the API to add our business logic by using the Triggers corresponding to the request.

Along with the triggers, there are request handlers that we can use to implement the custom business logic corresponding to a request.

Post Trigger

CRT

CRT Extension


问:
App Immediatley crashes once app runs with error ClassNotFoundException: Didn't find class application on path: DexPathList
Starting a new project and I am experiencing the following error... I have tried other solutions but seem to be dated

Steps I have tried:

Double checked plugins (listed below)

Instance Run (not listed)

tried using kapt in-place of annotationProccessor (produces a different error)

```<code>    Process: com.example.transfer_tracker, PID: 28953
    java.lang.RuntimeException: Unable to instantiate application com.example.transfer_tracker.CoreApplication package com.example.transfer_tracker: java.lang.ClassNotFoundException: Didn't find class "com.example.transfer_tracker.CoreApplication" on path: DexPathList[[dex file "/data/data/com.example.transfer_tracker/code_cache/.overlay/base.apk/classes4.dex", zip file "/data/app/~~zfKHJdy7wnPYBA_pfwtohQ==/com.example.transfer_tracker-gXT0kIH37Cwb7XaCDmovmg==/base.apk"],nativeLibraryDirectories=[/data/app/~~zfKHJdy7wnPYBA_pfwtohQ==/com.example.transfer_tracker-gXT0kIH37Cwb7XaCDmovmg==/lib/arm64, /system/lib64, /system_ext/lib64]]
        at android.app.LoadedApk.makeApplication(LoadedApk.java:1364)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6686)
        at android.app.ActivityThread.access$1500(ActivityThread.java:247)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2053)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.app.ActivityThread.main(ActivityThread.java:7839)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.transfer_tracker.CoreApplication" on path: DexPathList[[dex file "/data/data/com.example.transfer_tracker/code_cache/.overlay/base.apk/classes4.dex", zip file "/data/app/~~zfKHJdy7wnPYBA_pfwtohQ==/com.example.transfer_tracker-gXT0kIH37Cwb7XaCDmovmg==/base.apk"],nativeLibraryDirectories=[/data/app/~~zfKHJdy7wnPYBA_pfwtohQ==/com.example.transfer_tracker-gXT0kIH37Cwb7XaCDmovmg==/lib/arm64, /system/lib64, /system_ext/lib64]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:218)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
        at android.app.AppComponentFactory.instantiateApplication(AppComponentFactory.java:76)
        at androidx.core.app.CoreComponentFactory.instantiateApplication(CoreComponentFactory.java:52)
        at android.app.Instrumentation.newApplication(Instrumentation.java:1177)
        at android.app.LoadedApk.makeApplication(LoadedApk.java:1356)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6686)
        at android.app.ActivityThread.access$1500(ActivityThread.java:247)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2053)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.app.ActivityThread.main(ActivityThread.java:7839)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
        Suppressed: java.lang.NoClassDefFoundError: Failed resolution of: Lcom/example/transfer_tracker/Hilt_CoreApplication;
        at java.lang.VMClassLoader.findLoadedClass(Native Method)
        at java.lang.ClassLoader.findLoadedClass(ClassLoader.java:738)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:363)
                ... 15 more
     Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.transfer_tracker.Hilt_CoreApplication" on path: DexPathList[[dex file "/data/data/com.example.transfer_tracker/code_cache/.overlay/base.apk/classes4.dex", zip file "/data/app/~~zfKHJdy7wnPYBA_pfwtohQ==/com.example.transfer_tracker-gXT0kIH37Cwb7XaCDmovmg==/base.apk"],nativeLibraryDirectories=[/data/app/~~zfKHJdy7wnPYBA_pfwtohQ==/com.example.transfer_tracker-gXT0kIH37Cwb7XaCDmovmg==/lib/arm64, /system/lib64, /system_ext/lib64]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:218)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
                ... 18 more
        [CIRCULAR REFERENCE:java.lang.NoClassDefFoundError: Failed resolution of: Lcom/example/transfer_tracker/Hilt_CoreApplication;]
</code>```

Android Manifest

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.transfer_tracker">

    <application
        android:name=".CoreApplication"
        android:allowBackup="true"
        android:fullBackupContent="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.TransferTracker">
        <activity
            android:name=".login.LauncherActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

</code>```

Project build.gradle

```<code>buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:7.0.4"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.20"
        classpath 'com.google.dagger:hilt-android-gradle-plugin:2.40.5'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

Module project.gradle

```<code>plugins {
    id 'com.android.application'
    id 'kotlin-kapt'
    id 'kotlin-android'
    id 'dagger.hilt.android.plugin'
}

android {
    compileSdk 31

    defaultConfig {
        applicationId "com.example.transfer_tracker"
        minSdk 22
        targetSdk 31
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {
    implementation 'com.android.support:multidex:1.0.3'
    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.4.0'
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

    implementation 'com.google.dagger:hilt-android:2.40.5'
    annotationProcessor 'com.google.dagger:hilt-compiler:2.40.5'
}
</code>```

Application Class

```<code>package com.example.transfer_tracker

import android.app.Application
import androidx.multidex.MultiDexApplication
import dagger.hilt.android.HiltAndroidApp

@HiltAndroidApp
class CoreApplication : Application()
</code>```

when using kapt instead of annotationProccessor

```<code>public final class CoreApplication extends android.app.Application {
             ^
  Expected @HiltAndroidApp to have a value. Did you forget to apply the Gradle Plugin? (dagger.hilt.android.plugin)
  See https://dagger.dev/hilt/gradle-setup.html
  [Hilt] Processing did not complete. See error above for details.

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:kaptDebugKotlin'.
> A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptWithoutKotlincTask$KaptExecutionWorkAction
   > java.lang.reflect.InvocationTargetException (no error message)

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
</code>```

UPDATE

Implemented with Dagger2 error is gone... maybe this is due to a bug within the Hilt library

答:
Try extending the CoreApplication class with MultiDexApplication like this:

```<code>@HiltAndroidApp
class CoreApplication : MultiDexApplication() {...}
</code>```

Body:
Starting a new project and I am experiencing the following error... I have tried other solutions but seem to be dated

Steps I have tried:

Double checked plugins (listed below)

Instance Run (not listed)

tried using kapt in-place of annotationProccessor (produces a different error)

    Process: com.example.transfer_tracker, PID: 28953
    java.lang.RuntimeException: Unable to instantiate application com.example.transfer_tracker.CoreApplication package com.example.transfer_tracker: java.lang.ClassNotFoundException: Didn't find class "com.example.transfer_tracker.CoreApplication" on path: DexPathList[[dex file "/data/data/com.example.transfer_tracker/code_cache/.overlay/base.apk/classes4.dex", zip file "/data/app/~~zfKHJdy7wnPYBA_pfwtohQ==/com.example.transfer_tracker-gXT0kIH37Cwb7XaCDmovmg==/base.apk"],nativeLibraryDirectories=[/data/app/~~zfKHJdy7wnPYBA_pfwtohQ==/com.example.transfer_tracker-gXT0kIH37Cwb7XaCDmovmg==/lib/arm64, /system/lib64, /system_ext/lib64]]
        at android.app.LoadedApk.makeApplication(LoadedApk.java:1364)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6686)
        at android.app.ActivityThread.access$1500(ActivityThread.java:247)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2053)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.app.ActivityThread.main(ActivityThread.java:7839)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.transfer_tracker.CoreApplication" on path: DexPathList[[dex file "/data/data/com.example.transfer_tracker/code_cache/.overlay/base.apk/classes4.dex", zip file "/data/app/~~zfKHJdy7wnPYBA_pfwtohQ==/com.example.transfer_tracker-gXT0kIH37Cwb7XaCDmovmg==/base.apk"],nativeLibraryDirectories=[/data/app/~~zfKHJdy7wnPYBA_pfwtohQ==/com.example.transfer_tracker-gXT0kIH37Cwb7XaCDmovmg==/lib/arm64, /system/lib64, /system_ext/lib64]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:218)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
        at android.app.AppComponentFactory.instantiateApplication(AppComponentFactory.java:76)
        at androidx.core.app.CoreComponentFactory.instantiateApplication(CoreComponentFactory.java:52)
        at android.app.Instrumentation.newApplication(Instrumentation.java:1177)
        at android.app.LoadedApk.makeApplication(LoadedApk.java:1356)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6686)
        at android.app.ActivityThread.access$1500(ActivityThread.java:247)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2053)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.app.ActivityThread.main(ActivityThread.java:7839)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
        Suppressed: java.lang.NoClassDefFoundError: Failed resolution of: Lcom/example/transfer_tracker/Hilt_CoreApplication;
        at java.lang.VMClassLoader.findLoadedClass(Native Method)
        at java.lang.ClassLoader.findLoadedClass(ClassLoader.java:738)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:363)
                ... 15 more
     Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.transfer_tracker.Hilt_CoreApplication" on path: DexPathList[[dex file "/data/data/com.example.transfer_tracker/code_cache/.overlay/base.apk/classes4.dex", zip file "/data/app/~~zfKHJdy7wnPYBA_pfwtohQ==/com.example.transfer_tracker-gXT0kIH37Cwb7XaCDmovmg==/base.apk"],nativeLibraryDirectories=[/data/app/~~zfKHJdy7wnPYBA_pfwtohQ==/com.example.transfer_tracker-gXT0kIH37Cwb7XaCDmovmg==/lib/arm64, /system/lib64, /system_ext/lib64]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:218)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
                ... 18 more
        [CIRCULAR REFERENCE:java.lang.NoClassDefFoundError: Failed resolution of: Lcom/example/transfer_tracker/Hilt_CoreApplication;]

Android Manifest

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.transfer_tracker">

    <application
        android:name=".CoreApplication"
        android:allowBackup="true"
        android:fullBackupContent="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.TransferTracker">
        <activity
            android:name=".login.LauncherActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Project build.gradle

buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:7.0.4"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.20"
        classpath 'com.google.dagger:hilt-android-gradle-plugin:2.40.5'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Module project.gradle

plugins {
    id 'com.android.application'
    id 'kotlin-kapt'
    id 'kotlin-android'
    id 'dagger.hilt.android.plugin'
}

android {
    compileSdk 31

    defaultConfig {
        applicationId "com.example.transfer_tracker"
        minSdk 22
        targetSdk 31
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {
    implementation 'com.android.support:multidex:1.0.3'
    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.4.0'
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

    implementation 'com.google.dagger:hilt-android:2.40.5'
    annotationProcessor 'com.google.dagger:hilt-compiler:2.40.5'
}

Application Class

package com.example.transfer_tracker

import android.app.Application
import androidx.multidex.MultiDexApplication
import dagger.hilt.android.HiltAndroidApp

@HiltAndroidApp
class CoreApplication : Application()

when using kapt instead of annotationProccessor

public final class CoreApplication extends android.app.Application {
             ^
  Expected @HiltAndroidApp to have a value. Did you forget to apply the Gradle Plugin? (dagger.hilt.android.plugin)
  See https://dagger.dev/hilt/gradle-setup.html
  [Hilt] Processing did not complete. See error above for details.

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:kaptDebugKotlin'.
> A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptWithoutKotlincTask$KaptExecutionWorkAction
   > java.lang.reflect.InvocationTargetException (no error message)

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

UPDATE

Implemented with Dagger2 error is gone... maybe this is due to a bug within the Hilt library

Body:
Try extending the CoreApplication class with MultiDexApplication like this:

@HiltAndroidApp
class CoreApplication : MultiDexApplication() {...}


问:
On publish Entity Framework is connecting to the wrong database
I have Asp.Net Core 5.0 and Entity Framework 5.0.12. When I change the connection string I'm changing it in both appsettings.json and in ProgramContext. Then I do build and Publish in folder or Publish with FTP. Both times I make sure the publisher is using the correct connection string.

Then I deploy and I can see that on the deployed the publisher is using the old connection string. Please help how my newly published api to use the new connection string.

For those who will say put some code as example(so irrelevant) in appsettings.json I have

```<code>  "ConnectionStrings": {
    "DefaultConnection1": "Data Source=MyDatabaseServer;Initial Catalog=myDatabaseName;MyUser;Password=MyPassword"

</code>```

Then in services.cs I have

```<code>services.AddDbContext<MyContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection1")));
</code>```

in MyContext.cs I have

```<code>if (!optionsBuilder.IsConfigured)
 {
      optionsBuilder.UseSqlServer("Data Source=MyDatabaseServer;Initial Catalog=myDatabaseName;MyUser;Password=MyPassword");
 }
</code>```

and again when I try to print context.Database.GetConnectionString() I'm getting

```<code>Data Source=MyOldDatabaseServer;Initial Catalog=myOldDatabaseName;MyOldUser;Password=MyPassword
</code>```

Please help

答: It is not reading the wrong connection string. It is reading what it sees. There are a couple of reasons why this is happening. First, it is not overwritting the appsettings on the server with the new update you made on the local appsettings. in this case, simply manually update it on the server. Second, you have both appsettings.json and appsettings.development.json on the publish folder, one of them which the project reads might not be up to date. Just update it so the two appsettings have the same content. Once you figure out which of the appsettings it uses, you could just delete the unused one.</p>

Body:
I have Asp.Net Core 5.0 and Entity Framework 5.0.12. When I change the connection string I'm changing it in both appsettings.json and in ProgramContext. Then I do build and Publish in folder or Publish with FTP. Both times I make sure the publisher is using the correct connection string.

Then I deploy and I can see that on the deployed the publisher is using the old connection string. Please help how my newly published api to use the new connection string.

For those who will say put some code as example(so irrelevant) in appsettings.json I have

  "ConnectionStrings": {
    "DefaultConnection1": "Data Source=MyDatabaseServer;Initial Catalog=myDatabaseName;MyUser;Password=MyPassword"

Then in services.cs I have

services.AddDbContext<MyContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection1")));

in MyContext.cs I have

if (!optionsBuilder.IsConfigured)
 {
      optionsBuilder.UseSqlServer("Data Source=MyDatabaseServer;Initial Catalog=myDatabaseName;MyUser;Password=MyPassword");
 }

and again when I try to print context.Database.GetConnectionString() I'm getting

Data Source=MyOldDatabaseServer;Initial Catalog=myOldDatabaseName;MyOldUser;Password=MyPassword

Please help


问:
Reset asynchronous UIImageView before loading
My application hierarchy is as follows:

```<code>UINavigationController
|_____
      UITableViewController (display products summary with thumbnail image)
      |_____
            UIViewController (display product details with image)
</code>```

I'm using the following class to load images asynchronously in both UITableViewController and UIViewController since it was too slow to load the view as its getting the image from the internet

http://www.markj.net/iphone-asynchronous-table-image

I don't have any problem in UITableViewController, the problem is when the cell is clicked it loads the image in UIViewController, if I go back to UITableViewController then click another cell, the UIViewController opened with previous image until the new image loaded

How can I reset the UIImageView in UIViewController until the new image loaded?

This is the code to load the details view:

```<code>CGRect frame;
frame.size.width=240; frame.size.height=130;
frame.origin.x=0; frame.origin.y=0;
AsyncImageView* asyncImage = [[[AsyncImageView alloc] initWithFrame:frame] autorelease];
asyncImage.tag = 999;
NSURL *url = [NSURL URLWithString:@"http://i53.tinypic.com/5ezwc4.jpg"];
[asyncImage loadImageFromURL:url];
[detailsViewController.imgProduct addSubview:asyncImage];
</code>```

Please help.

答:
It worth enhancing the AsyncImageView class. Add your own init method, like this:

```
- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.image = [UIImage imageNamed:@"loading.png"];
    }
    return self;
}
```

The file loading.png must be in your bundle and contain something proper to show while the remote image is loading.

Body:
My application hierarchy is as follows:

UINavigationController
|_____
      UITableViewController (display products summary with thumbnail image)
      |_____
            UIViewController (display product details with image)

I'm using the following class to load images asynchronously in both UITableViewController and UIViewController since it was too slow to load the view as its getting the image from the internet

http://www.markj.net/iphone-asynchronous-table-image

I don't have any problem in UITableViewController, the problem is when the cell is clicked it loads the image in UIViewController, if I go back to UITableViewController then click another cell, the UIViewController opened with previous image until the new image loaded

How can I reset the UIImageView in UIViewController until the new image loaded?

This is the code to load the details view:

CGRect frame;
frame.size.width=240; frame.size.height=130;
frame.origin.x=0; frame.origin.y=0;
AsyncImageView* asyncImage = [[[AsyncImageView alloc] initWithFrame:frame] autorelease];
asyncImage.tag = 999;
NSURL *url = [NSURL URLWithString:@"http://i53.tinypic.com/5ezwc4.jpg"];
[asyncImage loadImageFromURL:url];
[detailsViewController.imgProduct addSubview:asyncImage];

Please help.

Body:
It worth enhancing the AsyncImageView class. Add your own init method, like this:

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.image = [UIImage imageNamed:@"loading.png"];
    }
    return self;
}

The file loading.png must be in your bundle and contain something proper to show while the remote image is loading.


问:
How do I get Git to view my project's files in Visual Studio Community 2022?
I'm referring to Git, as used by the GUI in VS Community 2022.

It seems like a simple question, but it doesn't look like anyone else has asked this question.

If you need more details, please ask.  Please don't just ignore this question.  Thanks.

答:
The 'git changes' viewer says there's no unstaged changes in the working directory, even though I changed and saved a source code file

Fall back temporarily to command-line, and check your file is not ignored:

```<code>cd /path/to/repository
git check-ignore -v -- folder/modified/file
</code>```

Double-check also the icon overlay symbol on those files, as shown here.

Body:
The 'git changes' viewer says there's no unstaged changes in the working directory, even though I changed and saved a source code file

Fall back temporarily to command-line, and check your file is not ignored:

cd /path/to/repository
git check-ignore -v -- folder/modified/file

Double-check also the icon overlay symbol on those files, as shown here.


问:
Azure FaceAPI Face is Not Found in Android Java
I am trying to build a face recognition attendance system using Azure FaceAPI. I created a face list. Then, I downloaded the images' URLs from firebase and then used the detection method to detect each face. I added each face to the face list. Finally, I wanted to test findSimilar method by giving it an existing face with the faces UUID array.
These are some parts of the code (I used a thread for each call)

```<code>private FaceServiceClient faceServiceClient=new FaceServiceRestClient("https://train.cognitiveservices.azure.com/face/v1.0/",key);
--
faceServiceClient.createFaceList(faceListId, "mylist", "recognition_04");
--
// in a loop from i=0 --> i < no of images
faces= faceServiceClient.detect(Urls.get(i), false, false, null);
facesIds.add( faceServiceClient.addFacesToFaceList(faceListId, Urls.get(i), null, faces[0].faceRectangle).persistedFaceId);
--
faceServiceClient.findSimilar(id,ids, 1 );

</code>```

I printed out all the IDs and checked that they exist. However, it always gives an error after calling findSimilar method.

```<code>com.microsoft.projectoxford.face.rest.ClientException: Face is not found.
</code>```

Can someone please tell me what the problem is?

答:
The answer was simply that findSimilar method takes the ID of detected face not a faceID from the faceList.
For me, I used an existing faceID just to test. However, I had to detect a face then get its ID.

```<code>faceServiceClient.findSimilar(id,ids, 1 );
</code>```

Summary: Replace 'id' with detected face ID.

Body:
I am trying to build a face recognition attendance system using Azure FaceAPI. I created a face list. Then, I downloaded the images' URLs from firebase and then used the detection method to detect each face. I added each face to the face list. Finally, I wanted to test findSimilar method by giving it an existing face with the faces UUID array.
These are some parts of the code (I used a thread for each call)

private FaceServiceClient faceServiceClient=new FaceServiceRestClient("https://train.cognitiveservices.azure.com/face/v1.0/",key);
--
faceServiceClient.createFaceList(faceListId, "mylist", "recognition_04");
--
// in a loop from i=0 --> i < no of images
faces= faceServiceClient.detect(Urls.get(i), false, false, null);
facesIds.add( faceServiceClient.addFacesToFaceList(faceListId, Urls.get(i), null, faces[0].faceRectangle).persistedFaceId);
--
faceServiceClient.findSimilar(id,ids, 1 );

I printed out all the IDs and checked that they exist. However, it always gives an error after calling findSimilar method.

com.microsoft.projectoxford.face.rest.ClientException: Face is not found.

Can someone please tell me what the problem is?

Body:
The answer was simply that findSimilar method takes the ID of detected face not a faceID from the faceList.
For me, I used an existing faceID just to test. However, I had to detect a face then get its ID.

faceServiceClient.findSimilar(id,ids, 1 );

Summary: Replace 'id' with detected face ID.


问:
Using images in pop-up in leaflet that remain within the HTML
I am creating an HTML file with leaflet and R for a proyect. The Idea is to add multiple markers in a map, and be able to click them and see a description as well as a picture. Here's an example code.

```<code>library(sp)
library(leaflet)
suppressPackageStartupMessages(library(imager))
coor<-c("11","-55","EG",
"12","-54","EG2")
df<-matrix(coor,ncol=3,byrow = TRUE)
df<-data.frame(lon=as.numeric(df[,1]),lat=as.numeric(df[,2]),Iden=df[,3])
descr<-c("Description written in popup.
         \n <img src=\"/A:/Path/FIle/Pics/EG.jpg\">",
"description 2 \n <img src=\"/A:/Path/FIle/Pics/EG_2.jpg\">")
df<-cbind.data.frame(df,descr)
colnames(df)[4]<-descr
coordinates(df) <- ~lat+lon
leaflet(df) %>% addMarkers(popup = ~descr,label = ~Iden) %>% addTiles()
</code>```

The picture is shown properly if I open the file in my PC, however, when using the file in another device, the image is not there, because the  img src is indicating a file location. What I want is to be able to export a single HTML file that contains the images in each pop-up, that can be oppened in any device.
How can I do this ?.

答:
You can encode the image into a URL using base64 (e.g see this web service)

Example Image: https://cdn.sstatic.net/Sites/stackoverflow/Img/favicon.ico?v=ec617d715196

Example HTML tag:

```<code><img src="data:image/x-icon;base64,[encoded data, 7240 characters]" />
</code>```

Body:
I am creating an HTML file with leaflet and R for a proyect. The Idea is to add multiple markers in a map, and be able to click them and see a description as well as a picture. Here's an example code.

library(sp)
library(leaflet)
suppressPackageStartupMessages(library(imager))
coor<-c("11","-55","EG",
"12","-54","EG2")
df<-matrix(coor,ncol=3,byrow = TRUE)
df<-data.frame(lon=as.numeric(df[,1]),lat=as.numeric(df[,2]),Iden=df[,3])
descr<-c("Description written in popup.
         \n ",
"description 2 \n ")
df<-cbind.data.frame(df,descr)
colnames(df)[4]<-descr
coordinates(df) <- ~lat+lon
leaflet(df) %>% addMarkers(popup = ~descr,label = ~Iden) %>% addTiles()

The picture is shown properly if I open the file in my PC, however, when using the file in another device, the image is not there, because the  img src is indicating a file location. What I want is to be able to export a single HTML file that contains the images in each pop-up, that can be oppened in any device.
How can I do this ?.

Body:
You can encode the image into a URL using base64 (e.g see this web service)

Example Image: https://cdn.sstatic.net/Sites/stackoverflow/Img/favicon.ico?v=ec617d715196

Example HTML tag:

<img src="data:image/x-icon;base64,[encoded data, 7240 characters]" />


问:
How to update Key Vault secret value without changing secret identifier?
Is there a way to change a Key Vault secret value without changing secret identifier ? I tried new version button in azure portal but the secret identifier changed .

thanks , Adam.

答:
Use the URL whitout the key:

https://kv-we-retrieve-kv-secret.vault.azure.net/secrets/MySecretValue/

Using the Secret Identifier like this, will reference the latest secret value.

Reference:
https://blog.eldert.net/reference-key-vault-secret-latest-version/

[...] However, often we will just want to reference the latest version, so we stay up to date even when the secret has been changed, for example because it is a rotating password.

It turns out, this is very easy, without the need to update the version number in all our applications whenever a new version is created. This is done by just omitting the version number from our link! So the will instead look like https://kv-we-retrieve-kv-secret.vault.azure.net/secrets/MySecretValue/.

Important to notice is the trailing slash ( / ), which needs to be included, otherwise you will just get a 404 error.[...]


问:
Python QTableWidget color of index and row with stylesheet
ist it possible to change the color of row and index in a Qtable widget via stylesheet in QT Designer???

```<code>    background-image: url(:/newPrefix/buttoooo.png);
QTableWidget{background-color: #e49e00;font: 75 12pt "Rockwell"}
QTableWidget:item:hover{ background-color: #fee103 }
QTableWidget:item:pressed{ background-color: #ff0000 }
QHeaderView{
Background-color:#e49e00;border-radius:15px;}
</code>```

答:
After long long search i found a solution for stylesheet:

´´´

```<code>QHeaderView::section:horizontal
{
    border-top: 0px solid #fffff8;
font: 75 14pt "MS Shell Dlg 2";
}

QHeaderView::section:vertical
{
    border-left: 0px solid #fffff8;
font: 75 14pt "MS Shell Dlg 2";
}
</code>```

´´´

Body:
ist it possible to change the color of row and index in a Qtable widget via stylesheet in QT Designer???

    background-image: url(:/newPrefix/buttoooo.png);
QTableWidget{background-color: #e49e00;font: 75 12pt "Rockwell"}
QTableWidget:item:hover{ background-color: #fee103 }
QTableWidget:item:pressed{ background-color: #ff0000 }
QHeaderView{
Background-color:#e49e00;border-radius:15px;}

Body:
After long long search i found a solution for stylesheet:

´´´

QHeaderView::section:horizontal
{
    border-top: 0px solid #fffff8;
font: 75 14pt "MS Shell Dlg 2";
}

QHeaderView::section:vertical
{
    border-left: 0px solid #fffff8;
font: 75 14pt "MS Shell Dlg 2";
}

´´´


问:
How to handle null and NULL value in sql
So I have been facing this weird situation in mysql where somehow null values are inserted in my table.
I'm talking about null value not NULL value.

I have attached image for better understating

as you can see name column have null and mobile_no have NULL

So after using this query

```<code>select Case when t1.name IS NULL then 'NA'
            when t1.name= 'NA' or 'null' or NULL then 'NA'
            else t1.name end as 'Name',
       Case when t1.mobile_no IS NULL then 'NA'
            when t1.mobile_no= 'NA' or 'null' or NULL then 'NA'
            else t1.mobile_noend as 'Mobile no' from student;
</code>```

after this I'm getting this result

```<code>|Name|Mobile no|
----------------
|null|NA       |
</code>```

but I want below result

```<code>|Name|Mobile no|
----------------
|NA  |NA       |
</code>```

答:
Can you try use IN statement? That should work.</p>
```<code>select Case WHEN (t1.name IN ('NA', 'null') OR t1.name IS NULL) THEN 'NA' else t1.name end as 'Name',
Case WHEN (t1.mobile IN ('NA', 'null') OR t1.mobile IS NULL) THEN 'NA' else t1.mobile_no end as 'Mobile no' from student;
</code>```

Body:
So I have been facing this weird situation in mysql where somehow null values are inserted in my table.
I'm talking about null value not NULL value.

I have attached image for better understating

as you can see name column have null and mobile_no have NULL

So after using this query

select Case when t1.name IS NULL then 'NA'
            when t1.name= 'NA' or 'null' or NULL then 'NA'
            else t1.name end as 'Name',
       Case when t1.mobile_no IS NULL then 'NA'
            when t1.mobile_no= 'NA' or 'null' or NULL then 'NA'
            else t1.mobile_noend as 'Mobile no' from student;

after this I'm getting this result

|Name|Mobile no|
----------------
|null|NA       |

but I want below result

|Name|Mobile no|
----------------
|NA  |NA       |

Body:
Can you try use IN statement? That should work.

select Case WHEN (t1.name IN ('NA', 'null') OR t1.name IS NULL) THEN 'NA' else t1.name end as 'Name',
Case WHEN (t1.mobile IN ('NA', 'null') OR t1.mobile IS NULL) THEN 'NA' else t1.mobile_no end as 'Mobile no' from student;


问:
Ansible Tower - How to pass Machine credentials as an extra vars to the job template?
The job template has an option for "Prompt on Launch" for credentials.

I want to pass the credentials name using extra vars. I'm launching these jobs through manageIQ and so I want the user to select the credentials and manageIQ should pass it as extra vars to AWX Tower.

Any idea what is the parameter for it? For example, in order to pass ssh username, we use "ansible_ssh_user".  I expect something similar is there for credentials? If that's possible would the value for the extra vars be just the credentials name?

I tried ansible_private_key_file as the extra vars name with the value Zabbix but I get the error that no such file exists (Zabbix).

My workaround right now is to store the ssh_key_file inside AWX container and when launching the job we set the ansible_private_key_file to /tmp/test.pem. But we actually want to select the name of the credentials from AWX tower instead of storing the keys inside the container.

答:
Any idea what is the parameter for it? ... I expect something similar is there for credentials? If that's possible would the value for the extra vars be just the credentials name?

According Ansible Tower documentation Credentials you can make (additional) credentials available via variable names and facts.

For Machine Credential you can get username and password parameters directly from facts:

vars:
  machine:
    username: '{{ ansible_user }}'
    password: '{{ ansible_password }}'
```
<p>For Network Credential which I use additionally in some playbooks I get username and password parameters from the job runtime environment via</p>
<pre class="lang-yaml prettyprint-override"><code>vars:
  network:
    username: '{{ lookup("env", "ANSIBLE_NET_USERNAME") }}'
    password: '{{ lookup("env", "ANSIBLE_NET_PASSWORD") }}'
</code>```

since currently there is no other way to specify two different machine credentials in one Job Template. Other Credential Names are listed in the documentation too.

To inject further credentials you could use

extra_vars:
  my_pass: '{{my_pass}}'
  my_user: '{{my_user}}'
```
<p>and access them with</p>
<pre class="lang-yaml prettyprint-override"><code>ansible_user: "{{ my_user }}"
ansible_password: "{{ my_pass }}"
</code>```

Even the direct way is working

ansible test --extra-vars="ansible_user=${ACCOUNT} ansible_password=${PASSWORD}" --become --module-name shell --args "echo $(hostname)"
```
<p>to make a connection. So in your case, your extra variables could be</p>
<pre class="lang-yaml prettyprint-override"><code>---
ansible_user: USER
ansible_password: PASSWORD
</code>```

or

--extra-vars="ansible_user=USER ansible_password=PASSWORD"
```

Thanks to

How Do I Use Ansible Tower's Credential Parameters (Machine, Network, Cloud) in my Playbook?

How To Use Multiple Machine Credentials For A Job Template In Ansible Tower?

Body:
Any idea what is the parameter for it? ... I expect something similar is there for credentials? If that's possible would the value for the extra vars be just the credentials name?

According Ansible Tower documentation Credentials you can make (additional) credentials available via variable names and facts.

For Machine Credential you can get username and password parameters directly from facts:

vars:
  machine:
    username: '{{ ansible_user }}'
    password: '{{ ansible_password }}'

For Network Credential which I use additionally in some playbooks I get username and password parameters from the job runtime environment via

vars:
  network:
    username: '{{ lookup("env", "ANSIBLE_NET_USERNAME") }}'
    password: '{{ lookup("env", "ANSIBLE_NET_PASSWORD") }}'

since currently there is no other way to specify two different machine credentials in one Job Template. Other Credential Names are listed in the documentation too.

To inject further credentials you could use

extra_vars:
  my_pass: '{{my_pass}}'
  my_user: '{{my_user}}'

and access them with

ansible_user: "{{ my_user }}"
ansible_password: "{{ my_pass }}"

Even the direct way is working

ansible test --extra-vars="ansible_user=${ACCOUNT} ansible_password=${PASSWORD}" --become --module-name shell --args "echo $(hostname)"

to make a connection. So in your case, your extra variables could be

---
ansible_user: USER
ansible_password: PASSWORD

or

--extra-vars="ansible_user=USER ansible_password=PASSWORD"

Thanks to

How Do I Use Ansible Tower's Credential Parameters (Machine, Network, Cloud) in my Playbook?

How To Use Multiple Machine Credentials For A Job Template In Ansible Tower?


问:
How do I change the date formatting of a column and determine the number of years in Jupyter?
I've been trying to figure out how to mass change the date formatting of my data (as there are millions of data on the dataset) using Jupyter Notebook as the two datasets given to me has a different date format. Tried to google for codes on how to change the date format but hasn't been successful. For example, I would like to change the date formatting for "Discharged" and the initial dataset after merging to a dataframe and the desired output would look something like this

Dataset (Merged using Dataframe)

ID
Age
Date Seen
Date Discharged

001
21
2019-10-22
02-02-2022 08:00:00PM

002
18
2013-05-24
15-05-2019 06:30:00PM

Desired Output

ID
Age
Date Seen
Date Discharged
Calculated Years (Round Up)

001
21
2019-10-22
2022-02-02
3

002
18
2013-05-24
2019-05-15
6

答:
Use dt.normalize:

```<code># Convert to datetime64 if it's not already the case
df['Date Seen'] = pd.to_datetime(df['Date Seen'])
df['Date Discharged'] = pd.to_datetime(df['Date Discharged'])

# Keep date part and compute years
df['Date Discharged'] = df['Date Discharged'].dt.normalize()
df['Years'] = df['Date Discharged'].dt.year - df['Date Seen'].dt.year
</code>```

Output:

```<code>>>> df
     ID  Age  Date Seen Date Discharged  Years
0   001   21 2019-10-22      2022-02-02      3
1   002   18 2013-05-24      2019-05-15      6
</code>```

Body:
Use dt.normalize:

# Convert to datetime64 if it's not already the case
df['Date Seen'] = pd.to_datetime(df['Date Seen'])
df['Date Discharged'] = pd.to_datetime(df['Date Discharged'])

# Keep date part and compute years
df['Date Discharged'] = df['Date Discharged'].dt.normalize()
df['Years'] = df['Date Discharged'].dt.year - df['Date Seen'].dt.year

Output:

>>> df
     ID  Age  Date Seen Date Discharged  Years
0   001   21 2019-10-22      2022-02-02      3
1   002   18 2013-05-24      2019-05-15      6


问:
Simple array rotation
I'm trying to solve a simple array problem and I have encountered some bug.

I input {1, 2, 3, 4, 5, 6} and rotate left by 2, it should give me {3, 4, 5, 6, 1, 2}

I cannot find a reason why it gives me {0, 0, 0, 0, 1, 2}
I think my code is correct. I do not like looking at answers but I looked it up but then I still don't see why it is giving me this wrong answer.

I've looked it through more than 1 hour and I still cannot figure it out so I joined this community. Please help me out...

```<code>public int[] rotate(int[] arr, int shift, int size) {
    int[] output = new int[size];
    for(int i = 0; i < output.length;i++) {
        int newIndex = (arr.length-shift+i) % arr.length;
        output[newIndex] = arr[i];
        }
    return output;
}
</code>```

My output:

答:
Although facing some list-conversion you could use the standard-library function Collections.rotate(List<?> list, int distance):

public static int[] rotate(int[] arr, int shift, int size) {
    //List<Integer> list = Arrays.asList(arr);  // only works with Wrapper-types not primitive
    var list = Arrays.stream(arr).boxed().collect(Collectors.toList());  // since Java 9: .toList();

    Collections.rotate(list, shift);

    int[] array = new int[size];  // can also be original: list.size() or arr.length
    for(int i = 0; i < size; i++) array[i] = list.get(i);

    return array;
}
```

Try the demo on IDEone.

For input {1, 2, 3, 4, 5, 6}; and a shift of 2 (to the right) it results in output:

[5, 6, 1, 2, 3, 4]

for a shift of -2 (to the left) it results in:

[3, 4, 5, 6, 1, 2]

See also:

Java, Shifting Elements in an Array

Converting array to list in Java

Convert list to array in Java

Title: Simple array rotation

Body:
I'm trying to solve a simple array problem and I have encountered some bug.

I input {1, 2, 3, 4, 5, 6} and rotate left by 2, it should give me {3, 4, 5, 6, 1, 2}

I cannot find a reason why it gives me {0, 0, 0, 0, 1, 2}
I think my code is correct. I do not like looking at answers but I looked it up but then I still don't see why it is giving me this wrong answer.

I've looked it through more than 1 hour and I still cannot figure it out so I joined this community. Please help me out...

public int[] rotate(int[] arr, int shift, int size) {
    int[] output = new int[size];
    for(int i = 0; i < output.length;i++) {
        int newIndex = (arr.length-shift+i) % arr.length;
        output[newIndex] = arr[i];
        }
    return output;
}

My output:

Body:
Although facing some list-conversion you could use the standard-library function Collections.rotate(List<?> list, int distance):

public static int[] rotate(int[] arr, int shift, int size) {
    //List<Integer> list = Arrays.asList(arr);  // only works with Wrapper-types not primitive
    var list = Arrays.stream(arr).boxed().collect(Collectors.toList());  // since Java 9: .toList();

    Collections.rotate(list, shift);

    int[] array = new int[size];  // can also be original: list.size() or arr.length
    for(int i = 0; i < size; i++) array[i] = list.get(i);

    return array;
}

Try the demo on IDEone.

For input {1, 2, 3, 4, 5, 6}; and a shift of 2 (to the right) it results in output:

[5, 6, 1, 2, 3, 4]

for a shift of -2 (to the left) it results in:

[3, 4, 5, 6, 1, 2]

See also:

Java, Shifting Elements in an Array

Converting array to list in Java

Convert list to array in Java


问:
Create characters like "aaa" and "baa" and so on till "zzz" in bash to a string
Help me to create characters in bash and add to a string in a orderly manner like</p>
```<code>AAA
AAB
AAC
AAD
AAE
...
ZZV
ZZW
ZZX
ZZY
ZZZ
</code>```

答:
User brace expansion:

for triple in {A..Z}{A..Z}{A..Z} ; do
    string+=$triple
done
```

Body:
Help me to create characters in bash and add to a string in a orderly manner like

AAA
AAB
AAC
AAD
AAE
...
ZZV
ZZW
ZZX
ZZY
ZZZ


问:
Get difference between two lists with Unique Entries
I have two lists in Python:

```<code>temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two']
</code>```

Assuming the elements in each list are unique, I want to create a third list with items from the first list which are not in the second list:

```<code>temp3 = ['Three', 'Four']
</code>```

Are there any fast ways without cycles and checking?

答:
this could be even faster than Mark's list comprehension:</p>

```<code>list(itertools.filterfalse(set(temp2).__contains__, temp1))
</code>```

Body:
I have two lists in Python:

temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two']

Assuming the elements in each list are unique, I want to create a third list with items from the first list which are not in the second list:

temp3 = ['Three', 'Four']

Are there any fast ways without cycles and checking?

Body:
this could be even faster than Mark's list comprehension:

list(itertools.filterfalse(set(temp2).__contains__, temp1))


答:
check you appsettings.json and  appsettings.development.json

then

clean Solution!

delete publish folder (local)

delete publish folder (server)

now publish and upload again

Title: On publish Entity Framework is connecting to the wrong database

Body:
I have Asp.Net Core 5.0 and Entity Framework 5.0.12. When I change the connection string I'm changing it in both appsettings.json and in ProgramContext. Then I do build and Publish in folder or Publish with FTP. Both times I make sure the publisher is using the correct connection string.

Then I deploy and I can see that on the deployed the publisher is using the old connection string. Please help how my newly published api to use the new connection string.

For those who will say put some code as example(so irrelevant) in appsettings.json I have

  "ConnectionStrings": {
    "DefaultConnection1": "Data Source=MyDatabaseServer;Initial Catalog=myDatabaseName;MyUser;Password=MyPassword"

Then in services.cs I have

services.AddDbContext<MyContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection1")));

in MyContext.cs I have

if (!optionsBuilder.IsConfigured)
 {
      optionsBuilder.UseSqlServer("Data Source=MyDatabaseServer;Initial Catalog=myDatabaseName;MyUser;Password=MyPassword");
 }

and again when I try to print context.Database.GetConnectionString() I'm getting

Data Source=MyOldDatabaseServer;Initial Catalog=myOldDatabaseName;MyOldUser;Password=MyPassword

Please help


问:
JSON Array to model using Alamofire
I'm creating a UITableView that will display this response in every cell.
The problem is, I do not know how to parse this response to the model.

Here is the response from the api

```<code>[
"electronics",
"jewelery",
"men's clothing",
"women's clothing"
]
</code>```

Here is the code for the the ViewController

```<code>class HomeViewController: UIViewController {

    @IBOutlet var tableView: UITableView!
    var category: [Category] = []
    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self

        guard let url = URL(string: "\(Constants.url.baseUrl)\(Constants.url.category)") else {
            return
        }

        AF.request(url).responseDecodable(of: [Category].self) { response in
            guard let categories = response.value else {
                return
            }
            DispatchQueue.main.async { [weak self] in

                self?.tableView.reloadData()
            }

        }

    }

}

extension HomeViewController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        print("category count", category.count)

        return category.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: Constants.identifiers.categoryTableViewCell) as? CategoryTableViewCell else{
            return UITableViewCell()
        }
        cell.configureTableViewCell(with: self.category[indexPath.row])
        return cell

    }

}
</code>```

Here is my model

```<code>struct Category: Codable {
}
</code>```

I would greatly appreciate any help. Thank you in advanced!

答:
If you really want a model class then decode as already suggested into a String array and then map the result to your model</p>
```<code>struct Category {
    let name: String
}

AF.request(url).responseDecodable(of: [String].self) { response in
    guard let categories = response.value else {
        return
    }
    DispatchQueue.main.async { [weak self] in
        self.category = categories.map(Category.init)
        self?.tableView.reloadData()
    }
}

</code>```

Title: JSON Array to model using Alamofire

Body:
I'm creating a UITableView that will display this response in every cell.
The problem is, I do not know how to parse this response to the model.

Here is the response from the api

[
"electronics",
"jewelery",
"men's clothing",
"women's clothing"
]

Here is the code for the the ViewController

class HomeViewController: UIViewController {

    @IBOutlet var tableView: UITableView!
    var category: [Category] = []
    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self

        guard let url = URL(string: "\(Constants.url.baseUrl)\(Constants.url.category)") else {
            return
        }

        AF.request(url).responseDecodable(of: [Category].self) { response in
            guard let categories = response.value else {
                return
            }
            DispatchQueue.main.async { [weak self] in

                self?.tableView.reloadData()
            }

        }

    }

}

extension HomeViewController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        print("category count", category.count)

        return category.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: Constants.identifiers.categoryTableViewCell) as? CategoryTableViewCell else{
            return UITableViewCell()
        }
        cell.configureTableViewCell(with: self.category[indexPath.row])
        return cell

    }

}

Here is my model

struct Category: Codable {
}

I would greatly appreciate any help. Thank you in advanced!

Body:
If you really want a model class then decode as already suggested into a String array and then map the result to your model

struct Category {
    let name: String
}

AF.request(url).responseDecodable(of: [String].self) { response in
    guard let categories = response.value else {
        return
    }
    DispatchQueue.main.async { [weak self] in
        self.category = categories.map(Category.init)
        self?.tableView.reloadData()
    }
}


问:
GCP Database Migration Service Test Step Error: Failed to create subnetwork
I'm tring migrate my Google Cloud RDS MySQL. I configured all the steps and had a test, got the error: Failed to create subnetwork. Please create Service Networking connection with service 'servicenetworking.googleapis.com' from consumer project 'xxx' network 'default' again.

I went through the diagnose guide, but found no solution about this error. Here's what I reviewed,
https://cloud.google.com/database-migration/docs/diagnose-issues

Where should I start from?

答:
I found the answer at Can't add private IP (VPC) to new Google Cloud SQL instance with gcloud

It's a VPC private connection service issue.


问:
Move images with respect to their names
I have 10 images (123.vid1.png, 123.vid5.png, 123.vid8.png, 146.vid1.png, 146.vid5.png, 146.vid6.png, 191.vid2.png, 191.vid2.png, 191.vid5.png, 191.vid10.png) in a folder. I want to move the images with their names (123, 146, 191) to their respective folder.
Folder 123 contains (123.vid1.png, 123.vid5.png, 123.vid8.png)
Folder 146 contains (146.vid1.png, 146.vid5.png, 146.vid6.png)
Folder 191 contains (191.vid2.png, 191.vid2.png, 191.vid5.png, 191.vid10.png)</p>
```<code>import os

path = "/home/samples/"
files = os.listdir(path)

def Convert(string):
    li = list(string.split(" "))
    return li

def unique(list1):
    list_set = set(list1)
    unique_list = (list(list_set))
    for x in unique_list:
        print (x)

for file in files:
    root, ext = os.path.splitext(file)
    name = root.split(".")[0]
    listing = Convert(name)
    print(listing)
</code>```

答:
```<code>def move_images_to_folders(list_of_images):
    for image in list_of_images:
        if image.split('.')[0] == '123':
            shutil.move(image, '123')
        elif image.split('.')[0] == '146':
            shutil.move(image, '146')
        elif image.split('.')[0] == '191':
            shutil.move(image, '191')

def main():
    list_of_images = os.listdir()
    move_images_to_folders(list_of_images)
</code>```
```<code>def move_images_to_folders(dir_path):
    import os
    import shutil
    import glob

    images = glob.glob(dir_path + '/*.png')
    folders = list(set([image.split('.')[0] for image in images]))
    for folder in folders:
        if not os.path.exists(dir_path + '/' + folder):
            os.makedirs(dir_path + '/' + folder)
    for image in images:
        shutil.move(image, dir_path + '/' + image.split('.')[0] + '/' + image)

if __name__ == '__main__':
    import sys
    dir_path = sys.argv[1]
    move_images_to_folders(dir_path)
    print('Done!')
</code>```

Haven't tested e2e. But this should do.

Title: Move images with respect to their names

Body:
I have 10 images (123.vid1.png, 123.vid5.png, 123.vid8.png, 146.vid1.png, 146.vid5.png, 146.vid6.png, 191.vid2.png, 191.vid2.png, 191.vid5.png, 191.vid10.png) in a folder. I want to move the images with their names (123, 146, 191) to their respective folder.
Folder 123 contains (123.vid1.png, 123.vid5.png, 123.vid8.png)
Folder 146 contains (146.vid1.png, 146.vid5.png, 146.vid6.png)
Folder 191 contains (191.vid2.png, 191.vid2.png, 191.vid5.png, 191.vid10.png)

import os

path = "/home/samples/"
files = os.listdir(path)

def Convert(string):
    li = list(string.split(" "))
    return li

def unique(list1):
    list_set = set(list1)
    unique_list = (list(list_set))
    for x in unique_list:
        print (x)

for file in files:
    root, ext = os.path.splitext(file)
    name = root.split(".")[0]
    listing = Convert(name)
    print(listing)

Body:
def move_images_to_folders(list_of_images):
    for image in list_of_images:
        if image.split('.')[0] == '123':
            shutil.move(image, '123')
        elif image.split('.')[0] == '146':
            shutil.move(image, '146')
        elif image.split('.')[0] == '191':
            shutil.move(image, '191')

def main():
    list_of_images = os.listdir()
    move_images_to_folders(list_of_images)

def move_images_to_folders(dir_path):
    import os
    import shutil
    import glob

    images = glob.glob(dir_path + '/*.png')
    folders = list(set([image.split('.')[0] for image in images]))
    for folder in folders:
        if not os.path.exists(dir_path + '/' + folder):
            os.makedirs(dir_path + '/' + folder)
    for image in images:
        shutil.move(image, dir_path + '/' + image.split('.')[0] + '/' + image)

if __name__ == '__main__':
    import sys
    dir_path = sys.argv[1]
    move_images_to_folders(dir_path)
    print('Done!')

Haven't tested e2e. But this should do.


问:
How to configure proxy in emulators in new versions of Android Studio?

Problem Description

I need to configure the proxy manually in my emulator through Android Studio. From the official Android documentation, it is suggested that this change can be made in the "settings" tab of the emulator's extended controls. The problem is that it seems to me that this documentation is outdated, as this setting is no longer displayed in the "settings" tab of the Android Studio emulators' extended controls.

Documentation

My Android Studio

My version of Android Studio

```<code>Android Studio Bumblebee | 2021.1.1
Build #AI-211.7628.21.2111.8092744, built on January 19, 2022
Runtime version: 11.0.11+9-b60-7590822 amd64
VM: OpenJDK 64-Bit Server VM by Oracle Corporation
Windows 10 10.0
GC: G1 Young Generation, G1 Old Generation
Memory: 1280M
Cores: 8
Registry: external.system.auto.import.disabled=true
Non-Bundled Plugins: com.wakatime.intellij.plugin (13.1.10), wu.seal.tool.jsontokotlin (3.7.2), org.jetbrains.kotlin (211-1.6.10-release-923-AS7442.40), com.developerphil.adbidea (1.6.4), org.jetbrains.compose.desktop.ide (1.0.0), ru.adelf.idea.dotenv (2021.2), org.intellij.plugins.markdown (211.7142.37)
</code>```

答:
You can open old emulator version by unchecking setting here

If you struggle to close your old emulator, try killing qemu... process

Body:
Problem Description

I need to configure the proxy manually in my emulator through Android Studio. From the official Android documentation, it is suggested that this change can be made in the "settings" tab of the emulator's extended controls. The problem is that it seems to me that this documentation is outdated, as this setting is no longer displayed in the "settings" tab of the Android Studio emulators' extended controls.

Documentation

My Android Studio

My version of Android Studio

Android Studio Bumblebee | 2021.1.1
Build #AI-211.7628.21.2111.8092744, built on January 19, 2022
Runtime version: 11.0.11+9-b60-7590822 amd64
VM: OpenJDK 64-Bit Server VM by Oracle Corporation
Windows 10 10.0
GC: G1 Young Generation, G1 Old Generation
Memory: 1280M
Cores: 8
Registry: external.system.auto.import.disabled=true
Non-Bundled Plugins: com.wakatime.intellij.plugin (13.1.10), wu.seal.tool.jsontokotlin (3.7.2), org.jetbrains.kotlin (211-1.6.10-release-923-AS7442.40), com.developerphil.adbidea (1.6.4), org.jetbrains.compose.desktop.ide (1.0.0), ru.adelf.idea.dotenv (2021.2), org.intellij.plugins.markdown (211.7142.37)


问:
how to add data to json file flutter?
i have a data.json file like this in which i am getting a list of data i want to add  another parameter{p_quantity} to this json file .
Or i can the parameter by default as empty then how i can i update that value .

```<code>[
  {
    "p_image": "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse1.mm.bing.net%2Fth%3Fid%3DOIP.qEvRk2ip9vubQ-_xnfTj1AHaFj%26pid%3DApi&f=1",
    "p_name":"Apple",
    "p_id":1,
    "p_cost":30,
    "p_availability":1,
    "p_details":"Imported from Swiss",
    "p_category":"Premium"
  },
  {
    "p_image": "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse3.mm.bing.net%2Fth%3Fid%3DOIP.l5ZNKHxygp8AHCJbVwlUaAHaE8%26pid%3DApi&f=1",
    "p_name":"Mango",
    "p_id":2,
    "p_cost":50,
    "p_availability":1,
    "p_details":"Farmed at Selam",
    "p_category":"Tamilnadu"
  },
  {
    "p_image": "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse2.mm.bing.net%2Fth%3Fid%3DOIP.hRWr-pLb_cF-gOn31CCSJgHaHa%26pid%3DApi&f=1",
    "p_name":"Bananna",
    "p_id":3,
    "p_cost":5,
    "p_availability":0
  },
  {
    "p_image": "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse2.mm.bing.net%2Fth%3Fid%3DOIP.FFvWgkIBYYekEc8BVt_wHgHaFW%26pid%3DApi&f=1",
    "p_name":"Orange",
    "p_id":4,
    "p_cost":25,
    "p_availability":1,
    "p_details":"from Nagpur",
    "p_category":"Premium"
  }
]
</code>```

in which i want to add another parameter "p_quantity" . how can i do that ?
I am getting the data via this function

```<code>Future<List<Products>> readJsonData() async {
  //read json file
  final jsondata = await rootBundle.rootBundle.loadString('assets/data.json');
  //decode json data as list
  final list = json.decode(jsondata) as List<dynamic>;
  //map json and initialize using DataModel
  return list.map((e) => Products.fromJson(e)).toList();
}
</code>```

and here is the product class

```<code>class  Products {
String? pImage;
String? pName;
int? pId;
int? pCost;
int? pAvailability;
String? pDetails;
String? pCategory;

Products(
{this.pImage,
this.pName,
this.pId,
this.pCost,
this.pAvailability,
this.pDetails,
this.pCategory});

Products.fromJson(Map<String, dynamic> json) {
pImage = json['p_image'];
pName = json['p_name'];
pId = json['p_id'];
pCost = json['p_cost'];
pAvailability = json['p_availability'];
pDetails = json['p_details'];
pCategory = json['p_category'];
}

Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['p_image'] = pImage;
data['p_name'] = pName;
data['p_id'] = pId;
data['p_cost'] = pCost;
data['p_availability'] = pAvailability;
data['p_details'] = pDetails;
data['p_category'] = pCategory;
return data;
}
}
</code>```

答:
You can add parameter p_quantity by manually in you json file like this

```<code>[
 {
   "p_image": "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse1.mm.bing.net%2Fth%3Fid%3DOIP.EvRk2ip9vubQ-_xnfTj1AHaFj%26pid%3DApi&f=1",
   "p_name": "Apple",
   "p_id": 1,
   "p_cost": 30,
   "p_availability": 1,
   "p_details": "Imported from Swiss",
   "p_category": "Premium",
   "p_quantity": 0
  },
  {
  "p_image": "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse3.mm.bing.net%2Fth%3Fid%3DOIP.l5ZNKHxygp8AHCJbVwlUaAHaE8%26pid%3DApi&f=1",
  "p_name": "Mango",
  "p_id": 2,
  "p_cost": 50,
  "p_availability": 1,
  "p_details": "Farmed at Selam",
  "p_category": "Tamilnadu",
  "p_quantity": 4
 },
 {
  "p_image": "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse2.mm.bing.net%2Fth%3Fid%3DOIP.hRWr-pLb_cF-gOn31CCSJgHaHa%26pid%3DApi&f=1",
  "p_name": "Bananna",
  "p_id": 3,
  "p_cost": 5,
  "p_availability": 0,
  "p_quantity": 1
 },
 {
  "p_image": "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse2.mm.bing.net%2Fth%3Fid%3DOIP.FFvWgkIBYYekEc8BVt_wHgHaFW%26pid%3DApi&f=1",
  "p_name": "Orange",
  "p_id": 4,
  "p_cost": 25,
  "p_availability": 1,
  "p_details": "from Nagpur",
  "p_category": "Premium",
  "p_quantity": 2
 }
]
</code>```

And your product class looks like

```<code>class  Products {
  String? pImage;
  String? pName;
  int? pId;
  int? pCost;
  int? pAvailability;
  int? pQuantity;
  String? pDetails;
  String? pCategory;

Products(
 {this.pImage,
  this.pName,
  this.pId,
  this.pCost,
  this.pAvailability,
  this.pDetails,
  this.pCategory,
  this.pQuantity});

Products.fromJson(Map<String, dynamic> json) {
  pImage = json['p_image'];
  pName = json['p_name'];
  pId = json['p_id'];
  pCost = json['p_cost'];
  pAvailability = json['p_availability'];
  pDetails = json['p_details'];
  pCategory = json['p_category'];
  pQuantity = json['p_quantity'];
}

Map<String, dynamic> toJson() {
  final Map<String, dynamic> data = <String, dynamic>{};
  data['p_image'] = pImage;
  data['p_name'] = pName;
  data['p_id'] = pId;
  data['p_cost'] = pCost;
  data['p_availability'] = pAvailability;
  data['p_details'] = pDetails;
  data['p_category'] = pCategory;
  data['p_quantity'] = pQuantity;
 return data;
 }
}
</code>```

Title: how to add data to json file flutter?

Body:
i have a data.json file like this in which i am getting a list of data i want to add  another parameter{p_quantity} to this json file .
Or i can the parameter by default as empty then how i can i update that value .

[
  {
    "p_image": "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse1.mm.bing.net%2Fth%3Fid%3DOIP.qEvRk2ip9vubQ-_xnfTj1AHaFj%26pid%3DApi&f=1",
    "p_name":"Apple",
    "p_id":1,
    "p_cost":30,
    "p_availability":1,
    "p_details":"Imported from Swiss",
    "p_category":"Premium"
  },
  {
    "p_image": "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse3.mm.bing.net%2Fth%3Fid%3DOIP.l5ZNKHxygp8AHCJbVwlUaAHaE8%26pid%3DApi&f=1",
    "p_name":"Mango",
    "p_id":2,
    "p_cost":50,
    "p_availability":1,
    "p_details":"Farmed at Selam",
    "p_category":"Tamilnadu"
  },
  {
    "p_image": "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse2.mm.bing.net%2Fth%3Fid%3DOIP.hRWr-pLb_cF-gOn31CCSJgHaHa%26pid%3DApi&f=1",
    "p_name":"Bananna",
    "p_id":3,
    "p_cost":5,
    "p_availability":0
  },
  {
    "p_image": "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse2.mm.bing.net%2Fth%3Fid%3DOIP.FFvWgkIBYYekEc8BVt_wHgHaFW%26pid%3DApi&f=1",
    "p_name":"Orange",
    "p_id":4,
    "p_cost":25,
    "p_availability":1,
    "p_details":"from Nagpur",
    "p_category":"Premium"
  }
]

in which i want to add another parameter "p_quantity" . how can i do that ?
I am getting the data via this function

Future<List<Products>> readJsonData() async {
  //read json file
  final jsondata = await rootBundle.rootBundle.loadString('assets/data.json');
  //decode json data as list
  final list = json.decode(jsondata) as List<dynamic>;
  //map json and initialize using DataModel
  return list.map((e) => Products.fromJson(e)).toList();
}

and here is the product class

class  Products {
String? pImage;
String? pName;
int? pId;
int? pCost;
int? pAvailability;
String? pDetails;
String? pCategory;

Products(
{this.pImage,
this.pName,
this.pId,
this.pCost,
this.pAvailability,
this.pDetails,
this.pCategory});

Products.fromJson(Map<String, dynamic> json) {
pImage = json['p_image'];
pName = json['p_name'];
pId = json['p_id'];
pCost = json['p_cost'];
pAvailability = json['p_availability'];
pDetails = json['p_details'];
pCategory = json['p_category'];
}

Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['p_image'] = pImage;
data['p_name'] = pName;
data['p_id'] = pId;
data['p_cost'] = pCost;
data['p_availability'] = pAvailability;
data['p_details'] = pDetails;
data['p_category'] = pCategory;
return data;
}
}

Body:
You can add parameter p_quantity by manually in you json file like this

[
 {
   "p_image": "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse1.mm.bing.net%2Fth%3Fid%3DOIP.EvRk2ip9vubQ-_xnfTj1AHaFj%26pid%3DApi&f=1",
   "p_name": "Apple",
   "p_id": 1,
   "p_cost": 30,
   "p_availability": 1,
   "p_details": "Imported from Swiss",
   "p_category": "Premium",
   "p_quantity": 0
  },
  {
  "p_image": "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse3.mm.bing.net%2Fth%3Fid%3DOIP.l5ZNKHxygp8AHCJbVwlUaAHaE8%26pid%3DApi&f=1",
  "p_name": "Mango",
  "p_id": 2,
  "p_cost": 50,
  "p_availability": 1,
  "p_details": "Farmed at Selam",
  "p_category": "Tamilnadu",
  "p_quantity": 4
 },
 {
  "p_image": "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse2.mm.bing.net%2Fth%3Fid%3DOIP.hRWr-pLb_cF-gOn31CCSJgHaHa%26pid%3DApi&f=1",
  "p_name": "Bananna",
  "p_id": 3,
  "p_cost": 5,
  "p_availability": 0,
  "p_quantity": 1
 },
 {
  "p_image": "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse2.mm.bing.net%2Fth%3Fid%3DOIP.FFvWgkIBYYekEc8BVt_wHgHaFW%26pid%3DApi&f=1",
  "p_name": "Orange",
  "p_id": 4,
  "p_cost": 25,
  "p_availability": 1,
  "p_details": "from Nagpur",
  "p_category": "Premium",
  "p_quantity": 2
 }
]

And your product class looks like

class  Products {
  String? pImage;
  String? pName;
  int? pId;
  int? pCost;
  int? pAvailability;
  int? pQuantity;
  String? pDetails;
  String? pCategory;

Products(
 {this.pImage,
  this.pName,
  this.pId,
  this.pCost,
  this.pAvailability,
  this.pDetails,
  this.pCategory,
  this.pQuantity});

Products.fromJson(Map<String, dynamic> json) {
  pImage = json['p_image'];
  pName = json['p_name'];
  pId = json['p_id'];
  pCost = json['p_cost'];
  pAvailability = json['p_availability'];
  pDetails = json['p_details'];
  pCategory = json['p_category'];
  pQuantity = json['p_quantity'];
}

Map<String, dynamic> toJson() {
  final Map<String, dynamic> data = <String, dynamic>{};
  data['p_image'] = pImage;
  data['p_name'] = pName;
  data['p_id'] = pId;
  data['p_cost'] = pCost;
  data['p_availability'] = pAvailability;
  data['p_details'] = pDetails;
  data['p_category'] = pCategory;
  data['p_quantity'] = pQuantity;
 return data;
 }
}


问:
Remove duplicates based on one column and keep latest entry in google sheets
I was working on some automation and wanted to remove the duplicate rows in my google sheet by comparing it on basis of 3rd column. I found one code which is working flawlessly but it does not remove the old entry in sheet, it removes the latest one. I wanted to keep the latest one from the duplicates.

This is the code which I found for appscript by Cooper:

```<code>function removeDuplicates() {
  var sh=SpreadsheetApp.getActiveSheet();
  var dt=sh.getDataRange().getValues();
  var uA=[];
  var d=0;
  for(var i=0;i<dt.length;i++) {
    if(uA.indexOf(dt[i][2])==-1) {
      uA.push(dt[i][2]);
    }else{
      sh.deleteRow(i+1-d++);
    }
  }
}
</code>```

Can anyone help me with the code which does the same work "removing duplicate rows (Keeps latest entry removes the old entry) based on column" ?

答:
My suggestion:

```<code>function myFunction() {
  var sh = SpreadsheetApp.getActiveSheet();

  // get values of column C
  var col = sh.getDataRange().getValues().map(x => x[2]);

  // get indexes of duplicated values in the column
  var duplicates = col.map((x,i) =>
    col.slice(i+1).includes(x) ? i+1 : '').filter(String);

  // remove rows by the indexes
  duplicates.reverse().forEach(x => sh.deleteRow(x));
}
</code>```

Before:

After:

Update

If there will some glitches it makes sense to add the command flush() after every deleteRow(). The last line of the code should be like this:

```<code>  // remove rows by the indexes
  duplicates.reverse().forEach(x => { sh.deleteRow(x); SpreadsheetApp.flush() });
</code>```

Body:
I was working on some automation and wanted to remove the duplicate rows in my google sheet by comparing it on basis of 3rd column. I found one code which is working flawlessly but it does not remove the old entry in sheet, it removes the latest one. I wanted to keep the latest one from the duplicates.

This is the code which I found for appscript by Cooper:

function removeDuplicates() {
  var sh=SpreadsheetApp.getActiveSheet();
  var dt=sh.getDataRange().getValues();
  var uA=[];
  var d=0;
  for(var i=0;i<dt.length;i++) {
    if(uA.indexOf(dt[i][2])==-1) {
      uA.push(dt[i][2]);
    }else{
      sh.deleteRow(i+1-d++);
    }
  }
}

Can anyone help me with the code which does the same work "removing duplicate rows (Keeps latest entry removes the old entry) based on column" ?

Body:
My suggestion:

function myFunction() {
  var sh = SpreadsheetApp.getActiveSheet();

  // get values of column C
  var col = sh.getDataRange().getValues().map(x => x[2]);

  // get indexes of duplicated values in the column
  var duplicates = col.map((x,i) =>
    col.slice(i+1).includes(x) ? i+1 : '').filter(String);

  // remove rows by the indexes
  duplicates.reverse().forEach(x => sh.deleteRow(x));
}

Before:

After:

Update

If there will some glitches it makes sense to add the command flush() after every deleteRow(). The last line of the code should be like this:

  // remove rows by the indexes
  duplicates.reverse().forEach(x => { sh.deleteRow(x); SpreadsheetApp.flush() });


问:
Problem with config Ingest RTMP to connect OBS to Restreamer: Could not access the specified channel or stream key

I want to use OBS to push a RTMP stream to Restreamer server. But I get error:

Could not access the specified channel or stream key, please
double-check your stream key. If it is correct, there may be a problem
connecting to the server.

Here a my configs:

Using Docker container to install Restreamer ( v0.6.8 )

```<code>sudo docker run -d --restart always \
     --name restreamer \
     -e "RS_USERNAME=admin" -e "RS_PASSWORD=test" -e "RS_TOKEN=test" \
     -p 8080:8080 -p 1935:1935/udp -p 1935:1935/tcp -v /mnt/restreamer/db:/restreamer/db \
     datarhei/restreamer:latest
</code>```

Setup for OBS:

I get error :

Please help me resolve this problem.

Thank you!

答:
The Stream Key is confusing, please try this:

Server: rtmp://xxx/live

Stream Key: external.stream?xxxx

Generally the Server should only set to the tcUrl of RTMP, while the stream should be in the Stream Key.

Body:
I want to use OBS to push a RTMP stream to Restreamer server. But I get error:

Could not access the specified channel or stream key, please
double-check your stream key. If it is correct, there may be a problem
connecting to the server.

Here a my configs:

Using Docker container to install Restreamer ( v0.6.8 )

sudo docker run -d --restart always \
     --name restreamer \
     -e "RS_USERNAME=admin" -e "RS_PASSWORD=test" -e "RS_TOKEN=test" \
     -p 8080:8080 -p 1935:1935/udp -p 1935:1935/tcp -v /mnt/restreamer/db:/restreamer/db \
     datarhei/restreamer:latest

Setup for OBS:

I get error :

Please help me resolve this problem.

Thank you!


问:
Check if a word exists in another string in c# without using any inbuilt function
```<code>string sentence = "This is a goodday";
string word = "good";
</code>```

I know this can be done with .Contains() method. I was asked in an interview how to do it without contains method.

答:
How about using a for loop?
Loop through the sentence checking for the first character of the work. Once you find that check for the next character of the word until you find the whole word (done - word exists in sentence) or a different character so you start again looking for the first character of the word until you run out of characters.

As the comments say, it would have been nicer to let us know what you answered.

Body:
string sentence = "This is a goodday";
string word = "good";

I know this can be done with .Contains() method. I was asked in an interview how to do it without contains method.