问:
Django Rest Framework: how to route a uuid to an associated object?
I am building a simple photos-albums app with Django Rest Framework (DRF). Each album has a UUID field in its model. I want to create 'share links' so that someone with a link of the form /albums/[uuid] will be able to access that album.

I am using ModelViewSet for my views, so I assume that the most succinct way to achieve this desired routing is via the action decorator, with urls like /albums/shared/[uuid], but it's not clear to me how to obtain the uuid in the action-decorated shared method. I can't even parse the URL because DRF will 404 before firing this shared method:

```<code>### views/album.py

class AlbumViewSet(viewsets.ModelViewSet):

    queryset = Album.objects.all()
    serializer_class = AlbumSerializer

    @action(detail=False, methods=['get'])
    def shared(self, request):

        # How do you get the uuid from the supplied URL?
        uuid = ???
        obj = self.get_queryset().objects.get(uuid=uuid)
        return Response([obj])
</code>```

Hopefully I won't have to add any fancy patterns to urls.py, but if I do then here is what I have so far:

```<code>### myapp/urls.py

router = routers.DefaultRouter()
router.register(r'albums', AlbumViewSet)
...

urlpatterns = [
    # ...
    path('', include(router.urls)),
]

format_suffix_patterns(urlpatterns)
</code>```

Thanks!

答:
The answer given by @Pradip is perfect but, for my own reference, here is a different solution I got working (except query part not tested!):</p>
```<code>### myapp/views/album.py

class AlbumViewSet(viewsets.ModelViewSet):
    ...

    @action(detail=False, methods=['get'],)
    def shared(self, request,   *args, **kwargs):
        uuid = kwargs.get('uuid', None)
        if uuid:
            try:
                obj = self.get_queryset().get(name=uuid)
                return Response([obj])
            except Album.DoesNotExist:
                obj = None
                raise exceptions.NotFound(f'Album with UUID {uuid} not found')
        else:
            raise exceptions.ParseError('UUID not parseable')

### myproject/urls.py
urlpatterns = [
    ...
    path('albums/<str:uuid>/shared/', AlbumViewSet.as_view({'get': 'shared'})),
]
</code>```

Body:
I am building a simple photos-albums app with Django Rest Framework (DRF). Each album has a UUID field in its model. I want to create 'share links' so that someone with a link of the form /albums/[uuid] will be able to access that album.

I am using ModelViewSet for my views, so I assume that the most succinct way to achieve this desired routing is via the action decorator, with urls like /albums/shared/[uuid], but it's not clear to me how to obtain the uuid in the action-decorated shared method. I can't even parse the URL because DRF will 404 before firing this shared method:

### views/album.py

class AlbumViewSet(viewsets.ModelViewSet):

    queryset = Album.objects.all()
    serializer_class = AlbumSerializer

    @action(detail=False, methods=['get'])
    def shared(self, request):

        # How do you get the uuid from the supplied URL?
        uuid = ???
        obj = self.get_queryset().objects.get(uuid=uuid)
        return Response([obj])

Hopefully I won't have to add any fancy patterns to urls.py, but if I do then here is what I have so far:

### myapp/urls.py

router = routers.DefaultRouter()
router.register(r'albums', AlbumViewSet)
...

urlpatterns = [
    # ...
    path('', include(router.urls)),
]

format_suffix_patterns(urlpatterns)

Thanks!

Body:
The answer given by @Pradip is perfect but, for my own reference, here is a different solution I got working (except query part not tested!):

### myapp/views/album.py

class AlbumViewSet(viewsets.ModelViewSet):
    ...

    @action(detail=False, methods=['get'],)
    def shared(self, request,   *args, **kwargs):
        uuid = kwargs.get('uuid', None)
        if uuid:
            try:
                obj = self.get_queryset().get(name=uuid)
                return Response([obj])
            except Album.DoesNotExist:
                obj = None
                raise exceptions.NotFound(f'Album with UUID {uuid} not found')
        else:
            raise exceptions.ParseError('UUID not parseable')

### myproject/urls.py
urlpatterns = [
    ...
    path('albums/<str:uuid>/shared/', AlbumViewSet.as_view({'get': 'shared'})),
]


来源: stackexchange

问:
WPF: "Value of type 'String' cannot be converted to 'System.Windows.Media.ImageSource'."
I'm trying to set a WPF Image's source.

XAML works:

```<code><Image Name="ImageThing"
       Source="images/Thing.png"/>
</code>```

Visual Basic fails:

```<code>ImageThing.Source = "images/Thing.png"
</code>```

…with this exception:

Value of type 'String' cannot be
  converted to
  'System.Windows.Media.ImageSource'.

How do I create the System.Windows.Media.ImageSource that I need?

Update

This code adapted from an MSDN example works:

```<code>Dim bmp As New BitmapImage()
bmp.BeginInit()
bmp.UriSource = New Uri("images/Thing.png", UriKind.Relative)
bmp.EndInit()
ImageThing.Source = bmp
</code>```

答:
Just change xaml file like this.

<Image Name="ImageThing">
    <Image.Source>
       <BitmapImage UriSource="images/Thing.png" />
    </Image.Source>
</Image>
```

OwnerDisplayName: Zack

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to set a WPF Image's source.

XAML works:

<Image Name="ImageThing"
       Source="images/Thing.png"/>

Visual Basic fails:

ImageThing.Source = "images/Thing.png"

…with this exception:

Value of type 'String' cannot be
  converted to
  'System.Windows.Media.ImageSource'.

How do I create the System.Windows.Media.ImageSource that I need?

Update

This code adapted from an MSDN example works:

Dim bmp As New BitmapImage()
bmp.BeginInit()
bmp.UriSource = New Uri("images/Thing.png", UriKind.Relative)
bmp.EndInit()
ImageThing.Source = bmp

LastEditorDisplayName: Zack

ContentLicense: CC BY-SA 3.0


问:
ChromeDriver and Chrome.exe doesnt close sometimes
I am facing problems with the chrome processes not closing after tests are done.

If i debug each testcase and also debug them by changing the test so the tests fail on purpose, the TearDown method is being always called and all processes are killed.

But sometimes and this happens in like 1 of 10 runs, some processes stay alive when not run in debug.

I found this issue report from 2018:
Chromedriver quit() method doesn't close all chrome.exe processes GITHUB
in which some people are facing the same issue.

In this link, there is not a fix mentioned.

Someone is mentioning in that link above that the reason could be caused by "Zombie processes" explained here:
Zombie Processes are Eating your Memory

Did anyone else face such issues?

答:
It may be happening because the tear down function as you mentioned is not called
first how do you call your tear down function ?</p>

ContentLicense: CC BY-SA 4.0


问:
Trying to change the colors of the first 3 bars in a bar graph using ggplot and scale_fill_manual
Hello I am trying to plot a bar graph with gglot, the graph has 20 values (20 bars) but I want the first 3 bars to fill in red and the rest in blue.  Here is my code but its not giving me my desired output, it is still showing all the bars in blue.

```<code>ggplot(data = my_data, aes(x=reorder(cat, -total), y=total))+
  geom_bar(stat = "identity", fill="blue")+
  scale_fill_manual(values=c("red","red","red"))+
  theme(axis.text.x = element_text(angle = 45, hjust=1))+
  scale_y_continuous(labels = comma)
</code>```

Greatful for all responses, thanks you.

答:
You need to map the x-axis variable to the fill aesthetic, and specify all the fill colors:

library(ggplot2)

my_data <- data.frame(total = round(runif(20) * 10000),
                 cat = LETTERS[1:20])

ggplot(my_data, aes(reorder(cat, -total), y = total)) +
  geom_col(aes(fill = reorder(cat, -total))) +
  scale_fill_manual(values = c(rep("red", 3), rep("blue", 17))) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  scale_y_continuous(labels = scales::comma) +
  theme(legend.position = "none")
```

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

Body:
Hello I am trying to plot a bar graph with gglot, the graph has 20 values (20 bars) but I want the first 3 bars to fill in red and the rest in blue.  Here is my code but its not giving me my desired output, it is still showing all the bars in blue.

ggplot(data = my_data, aes(x=reorder(cat, -total), y=total))+
  geom_bar(stat = "identity", fill="blue")+
  scale_fill_manual(values=c("red","red","red"))+
  theme(axis.text.x = element_text(angle = 45, hjust=1))+
  scale_y_continuous(labels = comma)

Greatful for all responses, thanks you.

Body:
You need to map the x-axis variable to the fill aesthetic, and specify all the fill colors:

library(ggplot2)

my_data <- data.frame(total = round(runif(20) * 10000),
                 cat = LETTERS[1:20])

ggplot(my_data, aes(reorder(cat, -total), y = total)) +
  geom_col(aes(fill = reorder(cat, -total))) +
  scale_fill_manual(values = c(rep("red", 3), rep("blue", 17))) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  scale_y_continuous(labels = scales::comma) +
  theme(legend.position = "none")

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


问:
XML Document Validation Error targetNamespace parameter
I have a schema with the following attributes:

```<code><xs:schema id="FooFile"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://Foostandards.com"
    elementFormDefault="qualified"
    xmlns="http://Foostandards.com">
</code>```

I have an XDocument constructor with the following attributes on the root tag (FooFile).

```<code>XDocument Foo2Xml = new XDocument(
    new XDeclaration("1.0", "utf-8", "yes"),
    new XComment("Foo2 file specifications implemented in xml"),
        new XElement("FooFile",
        new XAttribute(XNamespace.Xmlns + "xsi", "http://Foostandards.com"),
        new XAttribute(xsi + "schemaLocation", "http://Foostandards.com FooFile.xsd"), etc
</code>```

I get the following error logged when I run the XDocument Validate method:

"The targetNamespace parameter '' should be the same value as the
  targetNamespace 'http://Foostandards.com' of the schema."

I have the targetNamespace parameter in the Schema and I can't find info that tells me that it even belongs in the XML document attributes (or how to code it).

答: I ran into the same problem only after I added more than one XSD files into the XmlSchemaSet object.  It is strange that the VB console app seemed to work fine but in my ASP.NET app it threw an odd error stating the root element was not declared.  Some other forum threads suggested to add the targetNamespace and the associated xmlns attributes in the XSD file.  After adding those attributes to all my XSD files, I still ran into the same problem until I saw this forum describing exactly issue of having a "" in the first parameter when adding XSD into the XmlSchemaSet object.  By adding that parameter matching the targetNamespace in my XSD file, the exception was cleared.</p>

Body:
I have a schema with the following attributes:

<xs:schema id="FooFile"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://Foostandards.com"
    elementFormDefault="qualified"
    xmlns="http://Foostandards.com">

I have an XDocument constructor with the following attributes on the root tag (FooFile).

XDocument Foo2Xml = new XDocument(
    new XDeclaration("1.0", "utf-8", "yes"),
    new XComment("Foo2 file specifications implemented in xml"),
        new XElement("FooFile",
        new XAttribute(XNamespace.Xmlns + "xsi", "http://Foostandards.com"),
        new XAttribute(xsi + "schemaLocation", "http://Foostandards.com FooFile.xsd"), etc

I get the following error logged when I run the XDocument Validate method:

"The targetNamespace parameter '' should be the same value as the
  targetNamespace 'http://Foostandards.com' of the schema."

I have the targetNamespace parameter in the Schema and I can't find info that tells me that it even belongs in the XML document attributes (or how to code it).


问:
How to remove the rows containing all missing data in dplyr
I am trying to remove the rows from a tibble that contain missing values.

```<code>rawdata1 %>% group_by(TAXA) %>%
  filter(TAXA != "Annelida" & TAXA != "Arachnida" & TAXA != "Fungi" & TAXA != "Mammalia" & TAXA != "Platyhelminthes")%>%
  select(EGGSLAID,CRACKED,VIABLE,
         EMBRYLIVE,EGGHATCH,SURVIVE,GROWTH)%>%
  drop_na()
</code>```

But it keeps returning the same data:

TAXA
EGGSLAID
CRACKED
VIABLE
EMBRYLIVE

Crustacea
""
""
""
""

Crustacea
""
""
50%
""

Mollusca
""
""
""
""

Insecta
""
""
""
""

I think this is because it's not being recognised as NA but I don't know.

答:
Here is one option (assuming the structure of the empty string). Here, I convert the empty string to NA, then I get the sum of non-NA values for each row and keep only rows that have at least 1 non-NA value. Note: I also included @DanAdams better way of filtering):

```<code>library(tidyverse)

rawdata1 %>%
  group_by(TAXA) %>%
  filter(!TAXA %in% c(
    "Annelida",
    "Arachnida",
    "Fungi",
    "Mammalia",
    "Platyhelminthes"
  )) %>%
  select(TAXA, EGGSLAID, CRACKED, VIABLE,
         EMBRYLIVE) %>%
  mutate(across(everything(), ~ na_if(., "\"\""))) %>%
  rowwise() %>%
  filter(sum(!is.na(cur_data())) > 0)
</code>```

Output

```<code>  TAXA      EGGSLAID CRACKED VIABLE EMBRYLIVE
  <chr>     <chr>    <chr>   <chr>  <chr>
1 Crustacea NA       NA      50%    NA
</code>```

Data

```<code>rawdata1 <- structure(
  list(
    TAXA = c("Crustacea", "Crustacea", "Mollusca",
             "Insecta"),
    EGGSLAID = c("\"\"", "\"\"", "\"\"", "\"\""),
    CRACKED = c("\"\"",
                "\"\"", "\"\"", "\"\""),
    VIABLE = c("\"\"", "50%", "\"\"", "\"\""),
    EMBRYLIVE = c("\"\"", "\"\"", "\"\"", "\"\"")
  ),
  class = "data.frame",
  row.names = c(NA,-4L)
)
</code>```

Body:
I am trying to remove the rows from a tibble that contain missing values.

rawdata1 %>% group_by(TAXA) %>%
  filter(TAXA != "Annelida" & TAXA != "Arachnida" & TAXA != "Fungi" & TAXA != "Mammalia" & TAXA != "Platyhelminthes")%>%
  select(EGGSLAID,CRACKED,VIABLE,
         EMBRYLIVE,EGGHATCH,SURVIVE,GROWTH)%>%
  drop_na()

But it keeps returning the same data:

TAXA
EGGSLAID
CRACKED
VIABLE
EMBRYLIVE

Crustacea
""
""
""
""

Crustacea
""
""
50%
""

Mollusca
""
""
""
""

Insecta
""
""
""
""

I think this is because it's not being recognised as NA but I don't know.

Body:
Here is one option (assuming the structure of the empty string). Here, I convert the empty string to NA, then I get the sum of non-NA values for each row and keep only rows that have at least 1 non-NA value. Note: I also included @DanAdams better way of filtering):

library(tidyverse)

rawdata1 %>%
  group_by(TAXA) %>%
  filter(!TAXA %in% c(
    "Annelida",
    "Arachnida",
    "Fungi",
    "Mammalia",
    "Platyhelminthes"
  )) %>%
  select(TAXA, EGGSLAID, CRACKED, VIABLE,
         EMBRYLIVE) %>%
  mutate(across(everything(), ~ na_if(., "\"\""))) %>%
  rowwise() %>%
  filter(sum(!is.na(cur_data())) > 0)

Output

  TAXA      EGGSLAID CRACKED VIABLE EMBRYLIVE
  <chr>     <chr>    <chr>   <chr>  <chr>
1 Crustacea NA       NA      50%    NA

Data

rawdata1 <- structure(
  list(
    TAXA = c("Crustacea", "Crustacea", "Mollusca",
             "Insecta"),
    EGGSLAID = c("\"\"", "\"\"", "\"\"", "\"\""),
    CRACKED = c("\"\"",
                "\"\"", "\"\"", "\"\""),
    VIABLE = c("\"\"", "50%", "\"\"", "\"\""),
    EMBRYLIVE = c("\"\"", "\"\"", "\"\"", "\"\"")
  ),
  class = "data.frame",
  row.names = c(NA,-4L)
)


问:
Reactjs implementation of WebAssembly
I'm trying to get some wasm code in my react app but I can't seem to make it work.

I followed this tutorial, seems to have done the same but it doesn't work for me.

In my App.js I have this code:

```<code>import React, { useState } from 'react';
import waApi from './components/wa-api';

function App() {
  const [value, setValue] = useState(8);
  const [result, setResult] = useState();

  return (
    <div className="App">
      <p>
        The factorial of
        <input value={value} onChange={evt => setValue(evt.target.value)} />
        is {result}
      </p>
      <button onClick={async () => setResult((await waApi).factorial(value))}>
        Calculate
      </button>
    </div>
...
</code>```

and my code for the waApi is:

```<code>import {instantiateStreaming} from "assemblyscript/lib/loader";

export default instantiateStreaming(
    fetch('./wasm/as-api.wasm')
);
</code>```

I made sure that my wasm file is in the right place I have no probleme when running the App I have the right output:
web output

The problem is that when I press the calculate button nothing appears. It looks like the call isn't working or my result isn't updating and I don't know why.

This my first time using web assembly so I'm sorry if my question sounds stupid or something.

答:
The way to instantiate wasm is like this:

```<code>const { instance } = await WebAssembly.instantiateStreaming(fetch("/wasm/as-api.wasm"));
</code>```

your functions would then be under instance.exports. for example

```<code>instance.exports.factorial(3)
</code>```

see WebAssembly.instantiateStreaming() for examples

Title: Reactjs implementation of WebAssembly

Body:
I'm trying to get some wasm code in my react app but I can't seem to make it work.

I followed this tutorial, seems to have done the same but it doesn't work for me.

In my App.js I have this code:

import React, { useState } from 'react';
import waApi from './components/wa-api';

function App() {
  const [value, setValue] = useState(8);
  const [result, setResult] = useState();

  return (

        The factorial of
        <input value={value} onChange={evt => setValue(evt.target.value)} />
        is {result}

      <button onClick={async () => setResult((await waApi).factorial(value))}>
        Calculate
      </button>

...

and my code for the waApi is:

import {instantiateStreaming} from "assemblyscript/lib/loader";

export default instantiateStreaming(
    fetch('./wasm/as-api.wasm')
);

I made sure that my wasm file is in the right place I have no probleme when running the App I have the right output:
web output

The problem is that when I press the calculate button nothing appears. It looks like the call isn't working or my result isn't updating and I don't know why.

This my first time using web assembly so I'm sorry if my question sounds stupid or something.

Body:
The way to instantiate wasm is like this:

const { instance } = await WebAssembly.instantiateStreaming(fetch("/wasm/as-api.wasm"));

your functions would then be under instance.exports. for example

instance.exports.factorial(3)

see WebAssembly.instantiateStreaming() for examples


问:
maven repository not returning html text properly using python
I am trying to access the maven repository url, fetch the html data and print the title but it is showing wrong data. I am using python Beautiful Soup library. I believe something is wrong while fetching up the  html data. Can someone help here
CODE:

```<code>   from html.parser
   import HTMLParser
   from turtle import title
   import requests
   from bs4 import BeautifulSoup
   url= "https://mvnrepository.com/artifact/org.apache.maven/maven-plugin-api/3.8.3"
   r=requests.get(url)
   htmlcontent=r.content
   soup =BeautifulSoup(htmlcontent,'html.parser')
   print(soup.title)
</code>```

It is returning "Please Wait... | Cloudflare" which is wrong info.

答: Maven Repository is protected against robot requests and DDoS attacks with Cloudflare's (reverse proxy) CDN. That means that you first connect to cloudflare server, then, if you were allowed to continue, you will be redirected to original server. That's why you are getting Please Wait... as it's default DDoS protection waiting page.

Body:
I am trying to access the maven repository url, fetch the html data and print the title but it is showing wrong data. I am using python Beautiful Soup library. I believe something is wrong while fetching up the  html data. Can someone help here
CODE:

   from html.parser
   import HTMLParser
   from turtle import title
   import requests
   from bs4 import BeautifulSoup
   url= "https://mvnrepository.com/artifact/org.apache.maven/maven-plugin-api/3.8.3"
   r=requests.get(url)
   htmlcontent=r.content
   soup =BeautifulSoup(htmlcontent,'html.parser')
   print(soup.title)

It is returning "Please Wait... | Cloudflare" which is wrong info.


问:
EF SqlQuery throws not supported MultipleActiveResultSets exception if previous operation timeouts out
I have the following logic:

```<code>public async Task UpdateData(DbContext context)
{
    try
    {
        await LongUpdate(context);
    }
    catch (Exception e)
    {
        try
        {
            await context.Database.ExecuteSqlCommandAsync($@"update d set d.UpdatedAt = GETDATE() from SomeTable d where id > 11");
        }
        catch (Exception ex)
        {
            throw;
        }
    }
}
// this operations takes about 1 minute
private static async Task<int> LongUpdate(DbContext context)
{
    context.Database.CommandTimeout = 5; // change this to 15 to see MultipleActiveResultSets exception
    return await context.Database.SqlQuery<int>($@"update otherTable set UpdatedAt = GETDATE();SELECT @@ROWCOUNT").FirstOrDefaultAsync();
}
</code>```

As presented above there are two update operations both awaited.
LongUpdate takes more than minute.

When timeout is set to 5s:
LongUpdate throws timeout exception and the second update is executed successfully.

When I increase timeout to 15s or more:
LongUpdate throws timeout exception but second update immediately throws: System.InvalidOperationException: The connection does not support MultipleActiveResultSets..

Shouldn’t await prevent this exception?
Why this depends on timeout value?

答:
According to EF docs Database property should not be used in a way you do. So because it is as i think incorrect way we could not even consider what is happenning. All you db operations should go via Database Context using DbSet<T> with Save or SaveAsyncmethod ofDbContext` call after changes in datasets. Of course you could execute raw sql but other way like this:

public static IList<StockQuote> GetLast(this DbSet<StockQuote> dataSet, int stockId)
{
    IList<StockQuote> lastQuote = dataSet.FromSqlRaw("SELECT * FROM stockquote WHERE StockId = {0} ORDER BY Timestamp DESC LIMIT 1", new object[] { stockId })
                                         .ToList();
    return lastQuote;
}
```
<p>To create DbContext (in below example to MySql) with command timeout you coulde use something like this:</p>
<pre class="lang-cs prettyprint-override"><code>public static class ServiceCollectionExtension
{
    public static IServiceCollection ConfigureMySqlServerDbContext<TContext>(this IServiceCollection serviceCollection, string connectionString,
         ILoggerFactory loggerFactory, int timeout = 600)
            where TContext : DbContext
    {
        return serviceCollection.AddDbContext<TContext>(options => options.UseQueryTrackingBehavior(QueryTrackingBehavior.TrackAll)
                .UseLoggerFactory(loggerFactory)
                .UseMySql(connectionString, ServerVersion.AutoDetect(connectionString), sqlOptions => sqlOptions.CommandTimeout(timeout))
                .UseLazyLoadingProxies());
    }
}
</code>```

just call services.ConfigureMySqlServerDbContext<ModelContext>(Settings.ConnectionString, loggerFactory);

I think if you change your approach you get rid of exceptions.

Body:
I have the following logic:

public async Task UpdateData(DbContext context)
{
    try
    {
        await LongUpdate(context);
    }
    catch (Exception e)
    {
        try
        {
            await context.Database.ExecuteSqlCommandAsync($@"update d set d.UpdatedAt = GETDATE() from SomeTable d where id > 11");
        }
        catch (Exception ex)
        {
            throw;
        }
    }
}
// this operations takes about 1 minute
private static async Task<int> LongUpdate(DbContext context)
{
    context.Database.CommandTimeout = 5; // change this to 15 to see MultipleActiveResultSets exception
    return await context.Database.SqlQuery<int>($@"update otherTable set UpdatedAt = GETDATE();SELECT @@ROWCOUNT").FirstOrDefaultAsync();
}

As presented above there are two update operations both awaited.
LongUpdate takes more than minute.

When timeout is set to 5s:
LongUpdate throws timeout exception and the second update is executed successfully.

When I increase timeout to 15s or more:
LongUpdate throws timeout exception but second update immediately throws: System.InvalidOperationException: The connection does not support MultipleActiveResultSets..

Shouldn’t await prevent this exception?
Why this depends on timeout value?

Body:
According to EF docs Database property should not be used in a way you do. So because it is as i think incorrect way we could not even consider what is happenning. All you db operations should go via Database Context using DbSet<T> with Save or SaveAsyncmethod ofDbContext` call after changes in datasets. Of course you could execute raw sql but other way like this:

public static IList<StockQuote> GetLast(this DbSet<StockQuote> dataSet, int stockId)
{
    IList<StockQuote> lastQuote = dataSet.FromSqlRaw("SELECT * FROM stockquote WHERE StockId = {0} ORDER BY Timestamp DESC LIMIT 1", new object[] { stockId })
                                         .ToList();
    return lastQuote;
}

To create DbContext (in below example to MySql) with command timeout you coulde use something like this:

public static class ServiceCollectionExtension
{
    public static IServiceCollection ConfigureMySqlServerDbContext<TContext>(this IServiceCollection serviceCollection, string connectionString,
         ILoggerFactory loggerFactory, int timeout = 600)
            where TContext : DbContext
    {
        return serviceCollection.AddDbContext<TContext>(options => options.UseQueryTrackingBehavior(QueryTrackingBehavior.TrackAll)
                .UseLoggerFactory(loggerFactory)
                .UseMySql(connectionString, ServerVersion.AutoDetect(connectionString), sqlOptions => sqlOptions.CommandTimeout(timeout))
                .UseLazyLoadingProxies());
    }
}

just call services.ConfigureMySqlServerDbContext<ModelContext>(Settings.ConnectionString, loggerFactory);

I think if you change your approach you get rid of exceptions.


问:
Strict Mode Issue with Binding Arguments
I have an issue with running a test on my files. Would love if someone more experienced could help me out here.

the following code gives me this error:

error  Parsing error: Binding arguments in strict mode

```<code>return (...arguments) => {
  if (something){
    return [something]
  }
</code>```

答:
arguments is a special variable.

Use a different name.

```<code>function (...args) {
</code>```

Body:
I have an issue with running a test on my files. Would love if someone more experienced could help me out here.

the following code gives me this error:

error  Parsing error: Binding arguments in strict mode

return (...arguments) => {
  if (something){
    return [something]
  }

Body:
arguments is a special variable.

Use a different name.

function (...args) {


问:
Terraform interactive input doesn't work with the root module

Terraform Version

```<code>Terraform v1.1.2
on windows_amd64
</code>```

Terraform Configuration Files

child_module1.tf(C1):

```<code># Create Resource Group
resource "aws_resourcegroups_group" "resourcegroups_group" {
  name = "test"

  resource_query {
    query = <<JSON
{
  "ResourceTypeFilters": [
    "AWS::EC2::Instance"
  ],
  "TagFilters": [
    {
      "Key": "project",
      "Values": ["${var.ProjectName}"]
    }
  ]
}
JSON
  }
}
</code>```

child_module1_variables.tf:

```<code>########
variable "ProjectName" {
  type = string
  description = "This name would be prefixed with the cluster names."
}
</code>```

Now call this child module in another child module**(C2)**:
child_module2.tf:

```<code>module "prepare_aws_cloud" {
      source                        = "./modules/aws/prepare_cloud_copy"
      ProjectName                   = "${var.test.ProjectName}"
}
</code>```

child_module2_variables.tf:

```<code>variable "test" {
  type = object({
    ProjectName                 = string
  })
}
</code>```

Now I create a root module(R1)** which calls the child_module2.tf:**

```<code> terraform {
  backend "local" {
   }
 }
 module "test_deploy" {
   source = "D:\\REPO\\installer_v2.2.22.1\\installer\\aws"

test = {
    #ProjectName                 = ""
}

 }
</code>```

So the dependency is as follows:
R1 calls >> C2 calls >> C1

ERROR

```<code>PS D:\tkgTest> terraform apply -input=true
╷
│ Error: Invalid value for module argument
│
│   on testing.tf line 21, in module "test_deploy":
│   21: test= {
│   22:     #ProjectName                 = ""
│   23: }
│
│ The given value is not suitable for child module variable "test" defined at .terraform\modules\test_deploy\variables.tf:108,1-15: attribute "ProjectName" is required.
</code>```

Expected Behavior

I would have expected that the user input would be taken interactively by the console as I am passing the -input=true flag but it doesn't seem to work.

答:
The interactive prompts for input variables are intended only to help with getting started with Terraform (e.g. following a simple tutorial) and so they are limited in the scope of what they support. The typical way to set root module input variables for routine use is to either create a .tfvars file and pass it to Terraform with -var-file or to set a variable directly using -var.

Note also that only root module input variables can be set directly as part of the planning options. Any child module variables are defined exclusively by the expressions written in the module block, and so if you want to be able to set a child module's input variable on a per-run basis you'll need to also declare it as a root module variable and then pass it through to the child module.

For example, in the root module:

```<code>variable "test" {
  type = object({
    ProjectName                 = string
  })
}

module "test_deploy" {
  source = "./installer/aws"

  test = var.test
}
</code>```

You can then create an example.tfvars file with the following to set a value for the variable:

```<code>test = {
  ProjectName = "example"
}
</code>```

Specify that file when you run Terraform:

```<code>terraform apply -var-file=example.tfvars
</code>```

If you will always set the same values then you can avoid the need for the extra option by naming your file example.auto.tfvars and placing it in the same directory where you will run Terraform. Terraform will load .auto.tfvars files automatically without any explicit -var-file option.

Body:
Terraform Version

Terraform v1.1.2
on windows_amd64

Terraform Configuration Files

child_module1.tf(C1):

# Create Resource Group
resource "aws_resourcegroups_group" "resourcegroups_group" {
  name = "test"

  resource_query {
    query = <<JSON
{
  "ResourceTypeFilters": [
    "AWS::EC2::Instance"
  ],
  "TagFilters": [
    {
      "Key": "project",
      "Values": ["${var.ProjectName}"]
    }
  ]
}
JSON
  }
}

child_module1_variables.tf:

########
variable "ProjectName" {
  type = string
  description = "This name would be prefixed with the cluster names."
}

Now call this child module in another child module**(C2)**:
child_module2.tf:

module "prepare_aws_cloud" {
      source                        = "./modules/aws/prepare_cloud_copy"
      ProjectName                   = "${var.test.ProjectName}"
}

child_module2_variables.tf:

variable "test" {
  type = object({
    ProjectName                 = string
  })
}

Now I create a root module(R1)** which calls the child_module2.tf:**

 terraform {
  backend "local" {
   }
 }
 module "test_deploy" {
   source = "D:\\REPO\\installer_v2.2.22.1\\installer\\aws"

test = {
    #ProjectName                 = ""
}

 }

So the dependency is as follows:
R1 calls >> C2 calls >> C1

ERROR

PS D:\tkgTest> terraform apply -input=true
╷
│ Error: Invalid value for module argument
│
│   on testing.tf line 21, in module "test_deploy":
│   21: test= {
│   22:     #ProjectName                 = ""
│   23: }
│
│ The given value is not suitable for child module variable "test" defined at .terraform\modules\test_deploy\variables.tf:108,1-15: attribute "ProjectName" is required.

Expected Behavior

I would have expected that the user input would be taken interactively by the console as I am passing the -input=true flag but it doesn't seem to work.

Body:
The interactive prompts for input variables are intended only to help with getting started with Terraform (e.g. following a simple tutorial) and so they are limited in the scope of what they support. The typical way to set root module input variables for routine use is to either create a .tfvars file and pass it to Terraform with -var-file or to set a variable directly using -var.

Note also that only root module input variables can be set directly as part of the planning options. Any child module variables are defined exclusively by the expressions written in the module block, and so if you want to be able to set a child module's input variable on a per-run basis you'll need to also declare it as a root module variable and then pass it through to the child module.

For example, in the root module:

variable "test" {
  type = object({
    ProjectName                 = string
  })
}

module "test_deploy" {
  source = "./installer/aws"

  test = var.test
}

You can then create an example.tfvars file with the following to set a value for the variable:

test = {
  ProjectName = "example"
}

Specify that file when you run Terraform:

terraform apply -var-file=example.tfvars

If you will always set the same values then you can avoid the need for the extra option by naming your file example.auto.tfvars and placing it in the same directory where you will run Terraform. Terraform will load .auto.tfvars files automatically without any explicit -var-file option.


问:
How can i do onclick event with html,css,js
I want the css codes of the blog1popup class to change when the image is clicked.
I know how to do this with hover, but i don't know how to make this action happen by clicking.

The element I want to use as this button;

```<code><div class="row">
<div class="col-lg-4 col-md-6 sm-mb-35px">
   <div class="blog-item">
      <div class="img">
         <img src="assets/img/blog-grid-1.jpg" alt=""></a>
         <a href="" class="date"> <span class="day">14</span> <span class="month">April</span></a>
      </div>
      <a href="" class="title padding-30px"  style="margin-top: -1rem;">Fransa Geneline Islak Mendil İhracı</a>
      <p style="padding-left: 30px; padding-bottom: 20px; margin-top: -25px; line-height: 20px;">Tüm dünya ülkelerine yardımseverliği gösteren ülkemize..</p>
   </div>
</div>
</code>```

This is the element I want to have changes in the css codes.

Example on hover technique;

```<code>.blog-item:hover > .blog1popup{
opacity: 100%;
}
</code>```

答:
You can add click event on blog-item class, then you can add classes to any element or change any css property using jquery methods.

Eg.

$(".blog-item").on("click", function (e) {
  $(".blog1popup").css("opacity", "100%");
  $(".blog1popup").addClass("any-class");
});
```

Body:
I want the css codes of the blog1popup class to change when the image is clicked.
I know how to do this with hover, but i don't know how to make this action happen by clicking.

The element I want to use as this button;

          14 April

      Fransa Geneline Islak Mendil İhracı

Tüm dünya ülkelerine yardımseverliği gösteren ülkemize..

This is the element I want to have changes in the css codes.

Example on hover technique;

.blog-item:hover > .blog1popup{
opacity: 100%;
}


问:
How to use generic types in abstract class
I'm trying to write a base class with some methods I want they are implemented in the classes that they inherit from this class.

In this example:

```<code>abstract public class ServiceBase
{
    public ServiceBase()
    {
    }

    abstract public T Read<T>(string id);
    abstract public T Create<T>(T record);
    abstract public void Delete<T>(T record);
}

public class ServiceA: ServiceBase
{
    public Service(){}

    public override classA Read<classA>(string id)
    {
        ...
    }
    public override classA Create<classA>(classA record)
    {
        ...
    }
    public override void Delete<classA>(classA record)
    {
        ...
    }
}

public class ServiceB: ServiceBase
{
    public Service(){}

    public override classB Read<classB>(string id)
    {
        ...
    }
    public override classB Create<classB>(classB record)
    {
        ...
    }
    public override void Delete<classB>(classB record)
    {
        ...
    }
}
</code>```

this show the next error: "no suitable method found to override"

Is it possible to make this correct? How?

答:
This is similar to the accepted @jayGould answer, but with some additional tidbits to make it more inline with best practices.

I assume the target class for the service methods all have some commonality between them, and so it is useful to constrain ServiceBase<T> to use this common ancestor:

```<code>public interface IClass { }

public class ClassA  : IClass { }
public class ClassB  : IClass { }

abstract public class ServiceBase<T> where T:IClass
{
    protected ServiceBase() { }

    abstract public T Read(string id);
    abstract public T Create(T record);
    abstract public void Delete(T record);
}

public class ServiceA : ServiceBase<ClassA>
{
    public ServiceA() : base() { }

    public override ClassA Read(string id)
    {
        throw new NotImplementedException();
    }
    public override ClassA Create(ClassA record)
    {
        throw new NotImplementedException();
    }
    public override void Delete(ClassA record)
    {
        throw new NotImplementedException();
    }
}

public class ServiceB : ServiceBase<ClassB>
{
    public ServiceB() : base() { }

    public override ClassB Read(string id)
    {
        throw new NotImplementedException();
    }
    public override ClassB Create(ClassB record)
    {
        throw new NotImplementedException();
    }
    public override void Delete(ClassB record)
    {
        throw new NotImplementedException();
    }
}
</code>```

Additionally, an abstract class should only have protected constructors since they can only be called from derived classes.

Body:
I'm trying to write a base class with some methods I want they are implemented in the classes that they inherit from this class.

In this example:

abstract public class ServiceBase
{
    public ServiceBase()
    {
    }

    abstract public T Read<T>(string id);
    abstract public T Create<T>(T record);
    abstract public void Delete<T>(T record);
}

public class ServiceA: ServiceBase
{
    public Service(){}

    public override classA Read<classA>(string id)
    {
        ...
    }
    public override classA Create<classA>(classA record)
    {
        ...
    }
    public override void Delete<classA>(classA record)
    {
        ...
    }
}

public class ServiceB: ServiceBase
{
    public Service(){}

    public override classB Read<classB>(string id)
    {
        ...
    }
    public override classB Create<classB>(classB record)
    {
        ...
    }
    public override void Delete<classB>(classB record)
    {
        ...
    }
}

this show the next error: "no suitable method found to override"

Is it possible to make this correct? How?

Body:
This is similar to the accepted @jayGould answer, but with some additional tidbits to make it more inline with best practices.

I assume the target class for the service methods all have some commonality between them, and so it is useful to constrain ServiceBase<T> to use this common ancestor:

public interface IClass { }

public class ClassA  : IClass { }
public class ClassB  : IClass { }

abstract public class ServiceBase<T> where T:IClass
{
    protected ServiceBase() { }

    abstract public T Read(string id);
    abstract public T Create(T record);
    abstract public void Delete(T record);
}

public class ServiceA : ServiceBase<ClassA>
{
    public ServiceA() : base() { }

    public override ClassA Read(string id)
    {
        throw new NotImplementedException();
    }
    public override ClassA Create(ClassA record)
    {
        throw new NotImplementedException();
    }
    public override void Delete(ClassA record)
    {
        throw new NotImplementedException();
    }
}

public class ServiceB : ServiceBase<ClassB>
{
    public ServiceB() : base() { }

    public override ClassB Read(string id)
    {
        throw new NotImplementedException();
    }
    public override ClassB Create(ClassB record)
    {
        throw new NotImplementedException();
    }
    public override void Delete(ClassB record)
    {
        throw new NotImplementedException();
    }
}

Additionally, an abstract class should only have protected constructors since they can only be called from derived classes.


问:
React Navigation Authentication Flow: The action 'NAVIGATE' with payload {"name":"HomeScreen"} was not handled by any navigator
A beginner at React Native here, trying to combine this doc with AWS Amplify Authentication to implement React Navigation Authentication Flow but I can't seem to figure out what's wrong. Whenever I click on the login button,  this error  appears.

Navigation Code (excluding imports):

```<code>const NavigationGeneral = () => {

    const [user, setUser] = useState(undefined);

    const checkUser = async () => {
        try {
            const authUser = await Auth.currentAuthenticatedUser({bypassCache: true});
            setUser(authUser);
        } catch (e) {
            setUser(null);
        }
    }

    useEffect(() => {
        checkUser();
    }, []);

    if (user === undefined) {
        return (
            <View style = {{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
                <ActivityIndicator />
            </View>
        )
    }

    return (
        <Stack.Navigator screenOptions={{headerShown: false}}>
            {user ? (
                <>
                    <Stack.Screen name = "Login" component = {LoginScreen} />
                    <Stack.Screen name = "SignUp" component = {SignUpScreen} />
                    <Stack.Screen name = "ConfirmEmail" component = {ConfirmEmailScreen} />
                    <Stack.Screen name = "ForgotPassword" component = {ForgotPasswordScreen} />
                    <Stack.Screen name = "NewPassword" component = {NewPasswordScreen} />
                </>
            ): (
                <Stack.Screen name = "HomeScreen" component = {HomeTabNavigator} />
            )}
        </Stack.Navigator>
    );
};

//* TAB NAVIGATOR FOR APP SCREENS
const HomeTabNavigator = () => {
    return (
        <Tab.Navigator
            initialRouteName="Home"
            screenOptions={{
                headerShown: false,
                tabBarStyle: {backgroundColor: '#0052cc'},
                tabBarInactiveTintColor: '#fff',
                tabBarActiveTintColor: '#fff',
                tabBarActiveBackgroundColor: '#006600'
            }}>
            <Tab.Screen
                name="Home"
                component={HomeScreen}
                options={{
                tabBarLabel: 'Home',
                tabBarIcon: ({ color, size }) => (
                    <Ionicons name="home-outline" color={'#fff'} size={25} />
                ),
                }}
            />

            <Tab.Screen
                name="Courses"
                component={CourseScreen}
                options={{
                tabBarLabel: 'Courses',
                tabBarIcon: ({ color, size }) => (
                    <Ionicons name="library-outline" color={'#fff'} size={25} />
                ),
                }}
            />

            <Tab.Screen
                name="Profile"
                component={ProfileScreen}
                options={{
                tabBarLabel: 'My Profile',
                tabBarIcon: ({ color, size }) => (
                    <Ionicons name="person-outline" color={'#fff'} size={25} />
                ),
                }}
            />

            <Tab.Screen
                name="Forensic Tools"
                component={ForensicToolsScreen}
                options={{
                tabBarLabel: 'Tools List',
                tabBarIcon: ({ color, size }) => (
                    <Ionicons name="list-outline" color={'#fff'} size={25} />
                ),
                }}
            />

            <Tab.Screen
                name="Leaderboard"
                component={LeaderboardScreen}
                options={{
                tabBarLabel: 'Leaderboard',
                tabBarIcon: ({ color, size }) => (
                    <Ionicons name="podium-outline" color={'#fff'} size={25} />
                ),
                }}
            />

            <Tab.Screen
                name="Settings"
                component={SettingsScreen}
                options={{
                tabBarLabel: 'Settings',
                tabBarIcon: ({ color, size }) => (
                    <Ionicons name="settings-outline" color={'#fff'} size={25} />
                ),
                }}
            />
        </Tab.Navigator>
    );
};

export default NavigationGeneral;
</code>```

LoginScreen.js code snippet:

```<code>const onLoginPressed = async data => {
        if (loading) {
            return;
        }

        setLoading(true);
        try {
            await Auth.signIn(data.username, data.password);
            navigation.navigate("HomeScreen");
            console.log("Login");
        } catch (e) {
            Alert.alert('Oops', e.message);
        }
        setLoading(false);
    };
</code>```

I understand that I'm not supposed to manually navigate using navigation.navigate() but rather to conditionally define the screens. But whenever I remove navigation.navigate("HomeScreen"); from the code, nothing happens when I press the login button. So I assume something is wrong with my conditioning in my NavigationGeneral code, I just can't seem to figure out the problem.

Some help or additional tips would be greatly appreciated, thanks in advance. Please let me know if more info is required.

答:
You should not trigger navigation manually when implementing authentication flow with react-navigation. After the successful login, user will be truthy value. This means conditional rendering inside of navigation will handle it automatically.

Moreover, in case of condition user===undefined do not render LoadingIndicator, instead, create a new loading state and render LoadingIndicator when the state loading becomes true.

And I believe it should be !user instead of user, since not authenticated user (user===undefined) will want to see Login, Signup etc. screens.

```<code>return (
        <Stack.Navigator screenOptions={{headerShown: false}}>
           // Here it should be !user
            {!user ? (
                <>
                    <Stack.Screen name = "Login" component = {LoginScreen} />
                    <Stack.Screen name = "SignUp" component = {SignUpScreen} />
                    <Stack.Screen name = "ConfirmEmail" component = {ConfirmEmailScreen} />
                    <Stack.Screen name = "ForgotPassword" component = {ForgotPasswordScreen} />
                    <Stack.Screen name = "NewPassword" component = {NewPasswordScreen} />
                </>
            ): (
                <Stack.Screen name = "HomeScreen" component = {HomeTabNavigator} />
            )}
        </Stack.Navigator>
    );

</code>```
```<code>  const [checkAuthUserLoading, setCheckAuthUserLoading] = React.useState(false);
  const user = useSelector((state) => state.user); // Retrieve user from redux store. (It can be mobx, zustand or any other state management.)

  const checkUser = async () => {
    try {
      setCheckAuthUserLoading(true);
      const authUser = await Auth.currentAuthenticatedUser({
        bypassCache: true,
      });
      setCheckAuthUserLoading(false);
      dispatch(setAuthUser(user)); // I would suggest to use state management such as redux or mobx instead of storing user in component state
    } catch (e) {
      dispatch(setAuthUserError(e)); // Here you do not need to setUser(undefined) since its already failed and will be stay as undefined
    }
  };

  if (checkAuthUserLoading) {
    return <LoadingIndicator />;
  }
</code>```

Body:
A beginner at React Native here, trying to combine this doc with AWS Amplify Authentication to implement React Navigation Authentication Flow but I can't seem to figure out what's wrong. Whenever I click on the login button,  this error  appears.

Navigation Code (excluding imports):

const NavigationGeneral = () => {

    const [user, setUser] = useState(undefined);

    const checkUser = async () => {
        try {
            const authUser = await Auth.currentAuthenticatedUser({bypassCache: true});
            setUser(authUser);
        } catch (e) {
            setUser(null);
        }
    }

    useEffect(() => {
        checkUser();
    }, []);

    if (user === undefined) {
        return (
            <View style = {{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
                <ActivityIndicator />
            </View>
        )
    }

    return (
        <Stack.Navigator screenOptions={{headerShown: false}}>
            {user ? (
                <>
                    <Stack.Screen name = "Login" component = {LoginScreen} />
                    <Stack.Screen name = "SignUp" component = {SignUpScreen} />
                    <Stack.Screen name = "ConfirmEmail" component = {ConfirmEmailScreen} />
                    <Stack.Screen name = "ForgotPassword" component = {ForgotPasswordScreen} />
                    <Stack.Screen name = "NewPassword" component = {NewPasswordScreen} />
                </>
            ): (
                <Stack.Screen name = "HomeScreen" component = {HomeTabNavigator} />
            )}
        </Stack.Navigator>
    );
};

//* TAB NAVIGATOR FOR APP SCREENS
const HomeTabNavigator = () => {
    return (
        <Tab.Navigator
            initialRouteName="Home"
            screenOptions={{
                headerShown: false,
                tabBarStyle: {backgroundColor: '#0052cc'},
                tabBarInactiveTintColor: '#fff',
                tabBarActiveTintColor: '#fff',
                tabBarActiveBackgroundColor: '#006600'
            }}>
            <Tab.Screen
                name="Home"
                component={HomeScreen}
                options={{
                tabBarLabel: 'Home',
                tabBarIcon: ({ color, size }) => (
                    <Ionicons name="home-outline" color={'#fff'} size={25} />
                ),
                }}
            />

            <Tab.Screen
                name="Courses"
                component={CourseScreen}
                options={{
                tabBarLabel: 'Courses',
                tabBarIcon: ({ color, size }) => (
                    <Ionicons name="library-outline" color={'#fff'} size={25} />
                ),
                }}
            />

            <Tab.Screen
                name="Profile"
                component={ProfileScreen}
                options={{
                tabBarLabel: 'My Profile',
                tabBarIcon: ({ color, size }) => (
                    <Ionicons name="person-outline" color={'#fff'} size={25} />
                ),
                }}
            />

            <Tab.Screen
                name="Forensic Tools"
                component={ForensicToolsScreen}
                options={{
                tabBarLabel: 'Tools List',
                tabBarIcon: ({ color, size }) => (
                    <Ionicons name="list-outline" color={'#fff'} size={25} />
                ),
                }}
            />

            <Tab.Screen
                name="Leaderboard"
                component={LeaderboardScreen}
                options={{
                tabBarLabel: 'Leaderboard',
                tabBarIcon: ({ color, size }) => (
                    <Ionicons name="podium-outline" color={'#fff'} size={25} />
                ),
                }}
            />

            <Tab.Screen
                name="Settings"
                component={SettingsScreen}
                options={{
                tabBarLabel: 'Settings',
                tabBarIcon: ({ color, size }) => (
                    <Ionicons name="settings-outline" color={'#fff'} size={25} />
                ),
                }}
            />
        </Tab.Navigator>
    );
};

export default NavigationGeneral;

LoginScreen.js code snippet:

const onLoginPressed = async data => {
        if (loading) {
            return;
        }

        setLoading(true);
        try {
            await Auth.signIn(data.username, data.password);
            navigation.navigate("HomeScreen");
            console.log("Login");
        } catch (e) {
            Alert.alert('Oops', e.message);
        }
        setLoading(false);
    };

I understand that I'm not supposed to manually navigate using navigation.navigate() but rather to conditionally define the screens. But whenever I remove navigation.navigate("HomeScreen"); from the code, nothing happens when I press the login button. So I assume something is wrong with my conditioning in my NavigationGeneral code, I just can't seem to figure out the problem.

Some help or additional tips would be greatly appreciated, thanks in advance. Please let me know if more info is required.

Body:
You should not trigger navigation manually when implementing authentication flow with react-navigation. After the successful login, user will be truthy value. This means conditional rendering inside of navigation will handle it automatically.

Moreover, in case of condition user===undefined do not render LoadingIndicator, instead, create a new loading state and render LoadingIndicator when the state loading becomes true.

And I believe it should be !user instead of user, since not authenticated user (user===undefined) will want to see Login, Signup etc. screens.

return (
        <Stack.Navigator screenOptions={{headerShown: false}}>
           // Here it should be !user
            {!user ? (
                <>
                    <Stack.Screen name = "Login" component = {LoginScreen} />
                    <Stack.Screen name = "SignUp" component = {SignUpScreen} />
                    <Stack.Screen name = "ConfirmEmail" component = {ConfirmEmailScreen} />
                    <Stack.Screen name = "ForgotPassword" component = {ForgotPasswordScreen} />
                    <Stack.Screen name = "NewPassword" component = {NewPasswordScreen} />
                </>
            ): (
                <Stack.Screen name = "HomeScreen" component = {HomeTabNavigator} />
            )}
        </Stack.Navigator>
    );

  const [checkAuthUserLoading, setCheckAuthUserLoading] = React.useState(false);
  const user = useSelector((state) => state.user); // Retrieve user from redux store. (It can be mobx, zustand or any other state management.)

  const checkUser = async () => {
    try {
      setCheckAuthUserLoading(true);
      const authUser = await Auth.currentAuthenticatedUser({
        bypassCache: true,
      });
      setCheckAuthUserLoading(false);
      dispatch(setAuthUser(user)); // I would suggest to use state management such as redux or mobx instead of storing user in component state
    } catch (e) {
      dispatch(setAuthUserError(e)); // Here you do not need to setUser(undefined) since its already failed and will be stay as undefined
    }
  };

  if (checkAuthUserLoading) {
    return <LoadingIndicator />;
  }


问:
Is there a way to not inherit "virtualness" of a function in a subclass?
Is it possible in C++ to have a class override a virtual function, but only have virtual dispatch when the function is called through the superclass (ie. not when it is called on something statically typed as the subclass)? I know this isn't what happens, but is there any way to achieve something close?

The reason for wanting this is that I have two classes which both expose a flush() function. The vast majority of the time in my program, I am calling flush() directly on a subclass object that I know the type of, so I don't need virtual dispatch. However I want to add a superclass into the mix so that very infrequently I can pass a reference to an instance of either one of the classes into a doSomethingThenFlush() function, which would call flush() virtually.

I know I could use templates instead of virtual functions, and I know I could have two different functions (eg. flushVirtual() which just called flushNonVirtual(), and call flushNonVirtual() everywhere I don't need virtual dispatch). But these both seem a bit like throwing code at a problem which is largely syntactical. Is there any more elegant way to achieve this?

Perhaps more importantly, does anyone know why virtualness is inherited in C++?

```<code>struct Base
{
  virtual ~Base(){}
  virtual void func();
};

struct Derived : public Base
{
  void func(){}
};

void callVirtually(Base &base)
{
  base.func();//this will use virtual dispatch
}

void callStatically(Derived &derived)
{
  derived.func();//I don't want/need this to use virtual dispatch
}

int main()
{
  Derived derived;
  callVirtually(derived);
  callStatically(derived);
}
</code>```

答:
Virtualness is inherited because you don't know if someone is going to derive further from your Derived. Someone could just as well make a MoreDerived which could be passed to a function expecting a Derived&, and they'd be sad when they found that it was Derived's versions of all your virtual functions were bieng called instead of MoreDerived's.

If you mean that you won't ever inherit from Derived so you don't want to pay for a virtual function call, then you're out of luck, because C++ provides no way to promise that you won't ever inherit from a class, which would be necessary to do what you are wanting.

Body:
Is it possible in C++ to have a class override a virtual function, but only have virtual dispatch when the function is called through the superclass (ie. not when it is called on something statically typed as the subclass)? I know this isn't what happens, but is there any way to achieve something close?

The reason for wanting this is that I have two classes which both expose a flush() function. The vast majority of the time in my program, I am calling flush() directly on a subclass object that I know the type of, so I don't need virtual dispatch. However I want to add a superclass into the mix so that very infrequently I can pass a reference to an instance of either one of the classes into a doSomethingThenFlush() function, which would call flush() virtually.

I know I could use templates instead of virtual functions, and I know I could have two different functions (eg. flushVirtual() which just called flushNonVirtual(), and call flushNonVirtual() everywhere I don't need virtual dispatch). But these both seem a bit like throwing code at a problem which is largely syntactical. Is there any more elegant way to achieve this?

Perhaps more importantly, does anyone know why virtualness is inherited in C++?

struct Base
{
  virtual ~Base(){}
  virtual void func();
};

struct Derived : public Base
{
  void func(){}
};

void callVirtually(Base &base)
{
  base.func();//this will use virtual dispatch
}

void callStatically(Derived &derived)
{
  derived.func();//I don't want/need this to use virtual dispatch
}

int main()
{
  Derived derived;
  callVirtually(derived);
  callStatically(derived);
}


问:
How to filter date with golang and mongodb?
I'm trying to query records from mongodb using golang but seems like it's not working. I tried running the query with mongo cli using ISODate() and it works but I'm not sure how to call ISODate with golang. Below is a snippet of the code I'm running.

```<code>type Record struct{
    ID         primitive.ObjectID `bson:"_id"`
    PropertyID primitive.ObjectID `bson:"propertyID"`
    CreatedAt  primitive.DateTime `bson:"createdAt"`
}
// ....
cur, err := collection.Find(ctx, bson.M{"createdAt": bson.M{
    "$gte": time.Now().UTC().AddDate(-1, 0, 0).Format(time.RFC3339),
}})
// ....
var recs []Record
err = cur.All(ctx, &recs)
</code>```

if I run len(recs) I get 0 but in mongo-cli I'm getting result when I run code below.

```<code>db.getCollection('records').find({
    createdAt: {
        $gte: ISODate("2019-11-02T23:16:58+08:00")
    }
}).sort({createdAt: -1})
</code>```

by the way 2019-11-02T23:16:58+08:00 is the output of time.Now().UTC().AddDate(-1, 0, 0).Format(time.RFC3339)

Thanks in advance guys :D

答:
Here a simple sample using bson.D and aggregation:</p>
```<code>import "go.mongodb.org/mongo-driver/bson/primitive"

    mongo.Pipeline{
            {{"$match", bson.D{
                {"createdAt", bson.D{
    {"$gt", primitive.NewDateTimeFromTime(time.Now().AddDate(0, 0, -30))}}}},
            }}}
    }
</code>```

Body:
I'm trying to query records from mongodb using golang but seems like it's not working. I tried running the query with mongo cli using ISODate() and it works but I'm not sure how to call ISODate with golang. Below is a snippet of the code I'm running.

type Record struct{
    ID         primitive.ObjectID `bson:"_id"`
    PropertyID primitive.ObjectID `bson:"propertyID"`
    CreatedAt  primitive.DateTime `bson:"createdAt"`
}
// ....
cur, err := collection.Find(ctx, bson.M{"createdAt": bson.M{
    "$gte": time.Now().UTC().AddDate(-1, 0, 0).Format(time.RFC3339),
}})
// ....
var recs []Record
err = cur.All(ctx, &recs)

if I run len(recs) I get 0 but in mongo-cli I'm getting result when I run code below.

db.getCollection('records').find({
    createdAt: {
        $gte: ISODate("2019-11-02T23:16:58+08:00")
    }
}).sort({createdAt: -1})

by the way 2019-11-02T23:16:58+08:00 is the output of time.Now().UTC().AddDate(-1, 0, 0).Format(time.RFC3339)

Thanks in advance guys :D

Body:
Here a simple sample using bson.D and aggregation:

import "go.mongodb.org/mongo-driver/bson/primitive"

    mongo.Pipeline{
            {{"$match", bson.D{
                {"createdAt", bson.D{
    {"$gt", primitive.NewDateTimeFromTime(time.Now().AddDate(0, 0, -30))}}}},
            }}}
    }


问:
sort a singly linked list formed of 1, 2 and 0s by swapping the nodes through one traversal in C
I'm trying to solve the question that I need to sort a given linked list which values consist of 1, 2 and 0 by traversing the list only once and I need to swap the nodes not values.
my code is:

```<code>    #define max 3

void sortList(node **headRef)
{
    if(*headRef==NULL){
        return;
    }
    node* head[max];
    node*tail[max];
    node* curr=*headRef;
    int i;
    for(i=0; i<max; i++){
        head[i]=tail[i]=NULL;
    }
    while(curr!=NULL){
        i=curr->data;
        if(head[i]==NULL){
            head[i]=tail[i]=curr;
        }
        else{
            tail[i]=tail[i]->next=curr;
        }
        curr=curr->next;
    }
    for(int i=0, curr=(*headRef)=NULL; i<max; i++){
        if(head[i]!=NULL){
            if(*headRef==NULL){
                *headRef=head[i];
            }
            else{
                curr = curr->next =head[i];
            }
            curr=tail[i];
        }

    }
    curr->next=NULL;
}
</code>```

but it keep giving me an error and I don't know how to solve it if anyone can help me please.

答:
Your code is close, but it's a bit cumbersome.

Whenever I see parallel arrays indexed by the same [type of] index, I think of creating a struct. You have head[] and tail[] so I'd create a "bucket" struct.

The multiple assignments in a single line [although doable/legal] makes the code hard(er) to read. Note that:

```<code>x = y = z;
</code>```

Is no faster than:

```<code>x = z;
y = z;
</code>```

if z is a simple scalar. The compiler will generate the same code but the latter is often cleaner/clearer.

Your code may [or may not] handle all cases of lists that are missing one or more of the 0,1,2 values. That is, lists of the form:

```<code>0,0,0
1,1,1
2,2,2

0,1
0,2

1,2
</code>```

Using for loops here is also helps the code readability.

Here's the refactored code (I've compiled it, but not tested it):

```<code>#include <stdio.h>

#define max 3

typedef struct node node;
struct node {
    int value;
    node *next;
};

typedef struct {
    node *head;
    node *tail;
} list;

void
sortList(node **headRef)
{
    node *head = *headRef;
    node *tail;
    node *curr;
    node *next;

    if (head == NULL)
        return;

    list *buck;
    list buckets[max] = { 0 };

    // split into buckets
    for (curr = head;  curr != NULL;  curr = next) {
        next = curr->next;
        curr->next = NULL;

        buck = &buckets[curr->value];

        if (buck->head == NULL)
            buck->head = curr;
        else
            buck->tail->next = curr;

        buck->tail = curr;
    }

    // combine buckets into [new] single list
    head = NULL;
    tail = NULL;
    for (int i = 0;  i < max;  ++i) {
        buck = &buckets[i];

        // skip empty buckets
        if (buck->head == NULL)
            continue;

        // point to _first_ non-empty bucket
        if (head == NULL)
            head = buck->head;

        // append _next_ non-empty bucket
        else
            tail->next = buck->head;

        tail = buck->tail;
    }

    *headRef = head;
}
</code>```

Body:
I'm trying to solve the question that I need to sort a given linked list which values consist of 1, 2 and 0 by traversing the list only once and I need to swap the nodes not values.
my code is:

    #define max 3

void sortList(node **headRef)
{
    if(*headRef==NULL){
        return;
    }
    node* head[max];
    node*tail[max];
    node* curr=*headRef;
    int i;
    for(i=0; i<max; i++){
        head[i]=tail[i]=NULL;
    }
    while(curr!=NULL){
        i=curr->data;
        if(head[i]==NULL){
            head[i]=tail[i]=curr;
        }
        else{
            tail[i]=tail[i]->next=curr;
        }
        curr=curr->next;
    }
    for(int i=0, curr=(*headRef)=NULL; i<max; i++){
        if(head[i]!=NULL){
            if(*headRef==NULL){
                *headRef=head[i];
            }
            else{
                curr = curr->next =head[i];
            }
            curr=tail[i];
        }

    }
    curr->next=NULL;
}

but it keep giving me an error and I don't know how to solve it if anyone can help me please.

Body:
Your code is close, but it's a bit cumbersome.

Whenever I see parallel arrays indexed by the same [type of] index, I think of creating a struct. You have head[] and tail[] so I'd create a "bucket" struct.

The multiple assignments in a single line [although doable/legal] makes the code hard(er) to read. Note that:

x = y = z;

Is no faster than:

x = z;
y = z;

if z is a simple scalar. The compiler will generate the same code but the latter is often cleaner/clearer.

Your code may [or may not] handle all cases of lists that are missing one or more of the 0,1,2 values. That is, lists of the form:

0,0,0
1,1,1
2,2,2

0,1
0,2

1,2

Using for loops here is also helps the code readability.

Here's the refactored code (I've compiled it, but not tested it):

#include <stdio.h>

#define max 3

typedef struct node node;
struct node {
    int value;
    node *next;
};

typedef struct {
    node *head;
    node *tail;
} list;

void
sortList(node **headRef)
{
    node *head = *headRef;
    node *tail;
    node *curr;
    node *next;

    if (head == NULL)
        return;

    list *buck;
    list buckets[max] = { 0 };

    // split into buckets
    for (curr = head;  curr != NULL;  curr = next) {
        next = curr->next;
        curr->next = NULL;

        buck = &buckets[curr->value];

        if (buck->head == NULL)
            buck->head = curr;
        else
            buck->tail->next = curr;

        buck->tail = curr;
    }

    // combine buckets into [new] single list
    head = NULL;
    tail = NULL;
    for (int i = 0;  i < max;  ++i) {
        buck = &buckets[i];

        // skip empty buckets
        if (buck->head == NULL)
            continue;

        // point to _first_ non-empty bucket
        if (head == NULL)
            head = buck->head;

        // append _next_ non-empty bucket
        else
            tail->next = buck->head;

        tail = buck->tail;
    }

    *headRef = head;
}


问:
How to install CRM 2016 Required Components without internet access
I am installing Microsoft Dynamics CRM 2016 (Full Server Role) on an isolated Windows Server 2012 R2 which doesn't have internet access. This is a constraint I have to deal with so it is not even possible for me to 'temporay enable internet'. MSSQL 2012 is on a different box.

I've been able to manually download, copy the files, and install all prerequisites but two:

Microsoft Application Error Reporting

SQL Native Client

Where/how do I install these two remaining prerequisites?

Strange thing is I downloaded native client (and other SQL prereqs) from  Microsoft® SQL Server® 2012 Feature Pack page and native client show in program files.

I've also turned-on "Windows Error Reporting" thinking it might solve the "Microsoft Application Error Reporting" prerequisite.

I've looked at the Software requirements and no specific server role is specified. Do I need to install the "Application Server Role" ??? This is the only thing I can think of for the error reporting.

Any help is welcome!

答:
Update from 2022:
In addition, you may need to manually install these:

SQL System Clr Types (SQLSystemCLRTypes\SQLSysClrTypes_x64.msi): http://go.microsoft.com/fwlink/?LinkId=293645&clcid=0x409

SQL Server Management Objects (SQLSharedManagementObjects\SharedManagementObjects_x64): http://go.microsoft.com/fwlink/?LinkId=293644&clcid=0x409


问:
Android: How to access a file in the SD Card
I'm trying to access the image on the SD card using below code but I"m getting File not found exception. Can someone tell me a correct way to acess the file???</p>

```<code>new File("/mnt/sdcard/splah2.jpg")
</code>```

答:
try this,</p>

```<code>File f=new File("/sdcard/splah2.jpg");
</code>```

Body:
I'm trying to access the image on the SD card using below code but I"m getting File not found exception. Can someone tell me a correct way to acess the file???

new File("/mnt/sdcard/splah2.jpg")

Body:
try this,

File f=new File("/sdcard/splah2.jpg");


问:
How to make a pill shape button with HTML and CSS?
I'm trying to design a button that looks like the one in the snippet.  Is the approach taken best practice or is there a more obvious way of doing this?  Seems like a lot of overhead just to get the rounded edges.

#p1,#p2{
   height:25px;
   width:25px;
   border-radius:50% 0 0 50%;
   background-color:blue;
}

#p2{
   border-radius:0 50% 50% 0;
}

button{
   height:25px;
   width:75px;
   background-color:blue;
   border:none;
   color:white;
}

#container{
   display:flex;
   align-items:center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='container'>
   <p id='p1'></p>
   <button>Update</button>
   <p id='p2'></p>
</div></code>```

答:
All you need is to set a border-radius greater than the button's height. It gives you that pill shape. Like so :

button{
   height:25px;
   width:75px;
   border-radius: 30px;
   background-color:blue;
   border:none;
   color:white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button>Update</button></code>```

Body:
I'm trying to design a button that looks like the one in the snippet.  Is the approach taken best practice or is there a more obvious way of doing this?  Seems like a lot of overhead just to get the rounded edges.

#p1,#p2{
   height:25px;
   width:25px;
   border-radius:50% 0 0 50%;
   background-color:blue;
}

#p2{
   border-radius:0 50% 50% 0;
}

button{
   height:25px;
   width:75px;
   background-color:blue;
   border:none;
   color:white;
}

#container{
   display:flex;
   align-items:center;
}

   <button>Update</button>

Body:
All you need is to set a border-radius greater than the button's height. It gives you that pill shape. Like so :

button{
   height:25px;
   width:75px;
   border-radius: 30px;
   background-color:blue;
   border:none;
   color:white;
}

<button>Update</button>


问:
How can I forcefully change the padding inside a mat-expansion-panel-body?
so I just created an expansion panel and it's working fine (it's very hardcoded though). I need to, however, eliminate a padding entirely from the subpanel part and I can't find a proper way to do it.

Here's the panel:

https://i.stack.imgur.com/hLoKn.png

You can notice that there is a white border that I want to eliminate (upon inspection, in the div.mat-expansion-panel-body part, there is a padding. When I set it to 0, it fixes and the white borders vanish. I tried however the following in my .css:

```<code>div.mat-expansion-panel-body {
  padding: 0 !important;
}
</code>```

But it didn't work. If anyone's got a solution to fix that I'd be greatly appreciated.

答:
The mat-expansion-panel-body is created internaly by Material.

Such as another Material components, to apply changes (mainly styles) to these components is very hard.

The alternative to solve this problem is remove the emulated encapsulation from your component, setting to ViewEncapsulation.None. But, with that, the styles applied into your component (css selectors, like classes, tags, ids, etc) are available for all components of your application.

To prevent encapsulation styles problems into your application, is a good idea apply an #id to your component container (in this case, the mat-expansion-panel), and work your component style inside this #id CSS selector, like the example:

<mat-expansion-panel id="my-component-name-style-container">

</mat-expansion-panel>
```
<pre class="lang-css prettyprint-override"><code>#my-component-name-style-container mat-expansion-panel-body {
   padding: 0;
}
</code>```

The idea of apply a CSS #id selector with the component name is prevent that other components have the same style (more or less "encapsulated" into the #component-name style selector, which is available for all application components because the encapsulation is none).

I hope I've helped

Body:
so I just created an expansion panel and it's working fine (it's very hardcoded though). I need to, however, eliminate a padding entirely from the subpanel part and I can't find a proper way to do it.

Here's the panel:

https://i.stack.imgur.com/hLoKn.png

You can notice that there is a white border that I want to eliminate (upon inspection, in the div.mat-expansion-panel-body part, there is a padding. When I set it to 0, it fixes and the white borders vanish. I tried however the following in my .css:

div.mat-expansion-panel-body {
  padding: 0 !important;
}

But it didn't work. If anyone's got a solution to fix that I'd be greatly appreciated.

Body:
The mat-expansion-panel-body is created internaly by Material.

Such as another Material components, to apply changes (mainly styles) to these components is very hard.

The alternative to solve this problem is remove the emulated encapsulation from your component, setting to ViewEncapsulation.None. But, with that, the styles applied into your component (css selectors, like classes, tags, ids, etc) are available for all components of your application.

To prevent encapsulation styles problems into your application, is a good idea apply an #id to your component container (in this case, the mat-expansion-panel), and work your component style inside this #id CSS selector, like the example:

<mat-expansion-panel id="my-component-name-style-container">
   <!-- your content -->
</mat-expansion-panel>

#my-component-name-style-container mat-expansion-panel-body {
   padding: 0;
}

The idea of apply a CSS #id selector with the component name is prevent that other components have the same style (more or less "encapsulated" into the #component-name style selector, which is available for all application components because the encapsulation is none).

I hope I've helped


问:
ReactJS: how using queryselector variable out a function
I'm using this code:

export default function Naviguation() {

```<code>const overBtnMenu = () => {
    const navBars = document.querySelectorAll('.nav-bars')
    for (let i = 0; i < navBars.length; i++) {
        navBars[i].style.width = '40px'
    }
}

const outBtnMenu = () => {
    const navBars = document.querySelectorAll('.nav-bars')
    navBars[0].style.width = '20px'
    navBars[1].style.width = '30px'
    navBars[2].style.width = '20px'
}

return (
    <nav>
        <img src={img} className='nav-logo' alt="logo" />
        <div className='nav-btn-menu' onMouseEnter={overBtnMenu} onMouseLeave={outBtnMenu}>
            <span className='nav-barTop nav-bars'></span>
            <span className='nav-barMiddle nav-bars'></span>
            <span className='nav-barBottom nav-bars'></span>
        </div>
    </nav>
)
</code>```

}

the code runs correctly but I want to use the variable "navBars" once time like this

export default function Naviguation() {

```<code>const navBars = document.querySelectorAll('.nav-bars')

const overBtnMenu = () => {
    for (let i = 0; i < navBars.length; i++) {
        navBars[i].style.width = '40px'
    }
}

const outBtnMenu = () => {
    navBars[0].style.width = '20px'
    navBars[1].style.width = '30px'
    navBars[2].style.width = '20px'
}

return (
    <nav>
        <img src={img} className='nav-logo' alt="logo" />
        <div className='nav-btn-menu' onMouseEnter={overBtnMenu} onMouseLeave={outBtnMenu}>
            <span className='nav-barTop nav-bars'></span>
            <span className='nav-barMiddle nav-bars'></span>
            <span className='nav-barBottom nav-bars'></span>
        </div>
    </nav>
)
</code>```

}

But the code doesn't run because it wrote on the console "navBars undefined..."

How using a variable out the function to using it into my function?

答:
```<code>I wrote your code:
</code>```

import React, { useEffect, useRef } from 'react';
import img from "../../images/logo-sanimex.webp";

```<code>import "./Naviguation.css";

export default function Navigation() {
  const navBarsRef = useRef(null);
  const navBars = navBarsRef.current;

  useEffect(() => {
    navBarsRef.current = document.querySelectorAll('.nav-bars');
  }, []);

  const overBtnMenu = () => {
    for (let i = 0; i < navBars.length; i++) {
      navBars[i].style.width = '40px';
    }
  };

  const outBtnMenu = () => {
    navBars[0].style.width = '20px';
    navBars[1].style.width = '30px';
    navBars[2].style.width = '20px';
  };

  return (
    <nav>
      <img src={img} className="nav-logo" alt="logo" />
      <div className="nav-btn-menu" onMouseEnter={overBtnMenu} onMouseLeave={outBtnMenu}>
        <span className="nav-barTop nav-bars"></span>
        <span className="nav-barMiddle nav-bars"></span>
        <span className="nav-barBottom nav-bars"></span>
      </div>
    </nav>
  );
}

But it's still not working :(

console.log shows:

    Uncaught TypeError: navBars is null
        overBtnMenu Naviguation.js:15
</code>```

Body:
I'm using this code:

export default function Naviguation() {

const overBtnMenu = () => {
    const navBars = document.querySelectorAll('.nav-bars')
    for (let i = 0; i < navBars.length; i++) {
        navBars[i].style.width = '40px'
    }
}

const outBtnMenu = () => {
    const navBars = document.querySelectorAll('.nav-bars')
    navBars[0].style.width = '20px'
    navBars[1].style.width = '30px'
    navBars[2].style.width = '20px'
}

return (

)

}

the code runs correctly but I want to use the variable "navBars" once time like this

export default function Naviguation() {

const navBars = document.querySelectorAll('.nav-bars')

const overBtnMenu = () => {
    for (let i = 0; i < navBars.length; i++) {
        navBars[i].style.width = '40px'
    }
}

const outBtnMenu = () => {
    navBars[0].style.width = '20px'
    navBars[1].style.width = '30px'
    navBars[2].style.width = '20px'
}

return (

)

}

But the code doesn't run because it wrote on the console "navBars undefined..."

How using a variable out the function to using it into my function?

Body:
I wrote your code:

import React, { useEffect, useRef } from 'react';
import img from "../../images/logo-sanimex.webp";

import "./Naviguation.css";

export default function Navigation() {
  const navBarsRef = useRef(null);
  const navBars = navBarsRef.current;

  useEffect(() => {
    navBarsRef.current = document.querySelectorAll('.nav-bars');
  }, []);

  const overBtnMenu = () => {
    for (let i = 0; i < navBars.length; i++) {
      navBars[i].style.width = '40px';
    }
  };

  const outBtnMenu = () => {
    navBars[0].style.width = '20px';
    navBars[1].style.width = '30px';
    navBars[2].style.width = '20px';
  };

  return (
    <nav>
      <img src={img} className="nav-logo" alt="logo" />
      <div className="nav-btn-menu" onMouseEnter={overBtnMenu} onMouseLeave={outBtnMenu}>
        <span className="nav-barTop nav-bars"></span>
        <span className="nav-barMiddle nav-bars"></span>
        <span className="nav-barBottom nav-bars"></span>
      </div>
    </nav>
  );
}

But it's still not working :(

console.log shows:

    Uncaught TypeError: navBars is null
        overBtnMenu Naviguation.js:15


问:
What is the cause of the 'not found' error in my user-defined function?
```<code>df <- tibble(wspid = c("text","text",1:9,NA),
             PID = c("text","text",1:10))

#Function to export a single column inputted in the function argument
export_ids <- function(var) {

  export_df <- df %>%
    filter(!is.na(var)) %>%
    select(var)

  write_csv(export_df, "~/Downloads/final_ids.csv")

}

#Calling the function
export_ids(wspid)
</code>```

I keep getting the same error:

```<code>Error: Problem with `filter()` input `..1`.
ℹ Input `..1` is `!is.na(var)`.
x object 'wspid' not found
</code>```

I suspect there's some issue with the scoping of the function but no matter what combinations I try-- such as defining the tibble within the function or referencing the tibble directly within the function (as in, df$var) I still get an error.

答:
I guess a better solution would be to simply use:</p>
```<code>df <- tibble(wspid = c("text","text",1:9,NA),
             PID = c("text","text",1:10))

#Function to export a single column inputted in the function argument
export_ids <- function(df, var) {
    data <- df[[var]]
    # now filter out NA values
    data <- data[!is.na(data)]
    write_csv(data, "~/Downloads/final_ids.csv")
}

#Calling the function
export_ids(df, "wspid")
</code>```

Body:
df <- tibble(wspid = c("text","text",1:9,NA),
             PID = c("text","text",1:10))

#Function to export a single column inputted in the function argument
export_ids <- function(var) {

  export_df <- df %>%
    filter(!is.na(var)) %>%
    select(var)

  write_csv(export_df, "~/Downloads/final_ids.csv")

}

#Calling the function
export_ids(wspid)

I keep getting the same error:

Error: Problem with `filter()` input `..1`.
ℹ Input `..1` is `!is.na(var)`.
x object 'wspid' not found

I suspect there's some issue with the scoping of the function but no matter what combinations I try-- such as defining the tibble within the function or referencing the tibble directly within the function (as in, df$var) I still get an error.

Body:
I guess a better solution would be to simply use:

df <- tibble(wspid = c("text","text",1:9,NA),
             PID = c("text","text",1:10))

#Function to export a single column inputted in the function argument
export_ids <- function(df, var) {
    data <- df[[var]]
    # now filter out NA values
    data <- data[!is.na(data)]
    write_csv(data, "~/Downloads/final_ids.csv")
}

#Calling the function
export_ids(df, "wspid")


问:
JSF p:inputText is not coming in ManagedBean while file upload listener is called
I am using JSF 2.2.20. In the xhtml page, there is one input text field and a file upload (advanced mode) . But my problem is, while listener is called for file-upload, the input text is coming as empty. How can I get the input text? Help me out.

xhtml code snippet:

```<code>    <h:form id="formID" enctype="multipart/form-data" method="post">
        <p:growl id="growlId" sticky="true" showDetail="true"><p:autoUpdate /></p:growl>

        <p:outputPanel id="DocInfo">
            <h:panelGrid id="DocGrid" columns="3" style="margin-bottom:10px" cellpadding="8">

                <p:outputLabel for="upload_Doc_Name" value="Document Name :* " />
                <p:inputText id="upload_Doc_Name" value="#{uploadDocManagedBean.uploadDocName}"  style="font-size:8pt;width:230px" />

                <p:outputLabel for="projectUploadDocId" value="Choose File :* " style="font-weight:bold; float:left" />
                <p:fileUpload id="projectUploadDocId"  value="#{uploadDocManagedBean.uploadedFile}"  mode="advanced" dragDropSupport="true"
                        listener="#{uploadDocManagedBean.fileUploadListener}"  />

                <br/>

            </h:panelGrid>
        </p:outputPanel>
   </h:form>
</code>```

The managed bean code snippet:

```<code>    @ManagedBean(name = "uploadDocManagedBean")
        @ViewScoped
        public class UploadDocManagedBean implements Serializable {

       private static final long serialVersionUID = -1L;

        private String uploadDocName;
        private UploadedFile uploadedFile;
        public String getUploadDocName() {
                return uploadDocName;
        }

        public void setUploadDocName(String uploadDocName) {
            this.uploadDocName = uploadDocName;
        }
        public UploadedFile getUploadedFile() {
            return uploadedFile;
        }

        public void setUploadedFile(UploadedFile uploadedFile) {
            this.uploadedFile = uploadedFile;
        }

        public void fileUploadListener(FileUploadEvent fileUploadEvent) {
                try {
                    uploadedFile = fileUploadEvent.getFile();
                    String filename = uploadedFile.getFileName();

                    if (uploadDocName == null || uploadDocName.isEmpty()) {
                        String msg = "Document Name is empty.";
                        FacesContext.getCurrentInstance().addMessage("growlId",
                                new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, msg));
                        return;

                    }
                   } catch (Exception e) {
                    e.printStackTrace();
                }
        }
</code>```

In the managed bean, the uploadDocName is the coming as empty everytime, while this fileUploadListener() method is called.
What am I missing here?

答:
You can define process attribute on fileUpload. To make it simple, try with process="@form", it should work ;) By default, only fileUpload client id e.g @this is sent to the server for processing

More details for fileUpload component, see here: https://primefaces.github.io/primefaces/11_0_0/#/components/fileupload

Body:
I am using JSF 2.2.20. In the xhtml page, there is one input text field and a file upload (advanced mode) . But my problem is, while listener is called for file-upload, the input text is coming as empty. How can I get the input text? Help me out.

xhtml code snippet:

    <h:form id="formID" enctype="multipart/form-data" method="post">

            <h:panelGrid id="DocGrid" columns="3" style="margin-bottom:10px" cellpadding="8">

            </h:panelGrid>

   </h:form>

The managed bean code snippet:

    @ManagedBean(name = "uploadDocManagedBean")
        @ViewScoped
        public class UploadDocManagedBean implements Serializable {

       private static final long serialVersionUID = -1L;

        private String uploadDocName;
        private UploadedFile uploadedFile;
        public String getUploadDocName() {
                return uploadDocName;
        }

        public void setUploadDocName(String uploadDocName) {
            this.uploadDocName = uploadDocName;
        }
        public UploadedFile getUploadedFile() {
            return uploadedFile;
        }

        public void setUploadedFile(UploadedFile uploadedFile) {
            this.uploadedFile = uploadedFile;
        }

        public void fileUploadListener(FileUploadEvent fileUploadEvent) {
                try {
                    uploadedFile = fileUploadEvent.getFile();
                    String filename = uploadedFile.getFileName();

                    if (uploadDocName == null || uploadDocName.isEmpty()) {
                        String msg = "Document Name is empty.";
                        FacesContext.getCurrentInstance().addMessage("growlId",
                                new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, msg));
                        return;

                    }
                   } catch (Exception e) {
                    e.printStackTrace();
                }
        }

In the managed bean, the uploadDocName is the coming as empty everytime, while this fileUploadListener() method is called.
What am I missing here?


问:
How to swap digits in number?
I need to write function that gets 3 params(int num, int k, int nDigit).
The function get number and replace the digit inside the number in k index by nDigit.

for example:

```<code> int num  = 5498
 int k  = 2
 int nDigit= 3

the result is num = 5398
</code>```

My question is how can I implement it?I undastand that the best way to convert the num to string and then just replace char on specific index by nDigit char.

But is there any way to implement it?Without

答:
This is my javascript solution.

```<code> const solution = numbers => {   //declare a variable that will hold
the array el that is not strictly ascending   let flawedIndex;
      //declare a boolean variable to actually check if there is a flawed array el in the given array   let flawed = false;
      //iterate through the given array   for(let i=0; i<numbers.length; i++) {

     //check if current array el is greater than the next
     if(numbers[i] > numbers[i+1])
       {
         //check if we already set flawed to true once.
         //if flawed==true, then return that this array cannot be sorted
         //strictly ascending even if we swap one elements digits

         if(flawed) {

           return false;
         }

         //if flawed is false, then set it to true and store the index of the flawed array el
         else {

                            flawed = true;
                        flawedIndex = i;
                                }
       }
        }
      //if flawed is still false after the end of the for loop, return true    //where true = the array is sctrictly ascending   if(flawed ==
 false) return true;
      //if flawed==true, that is there is an array el that is flawed   if(flawed){

     //store the result of calling the swap function on the digits of the flawed array el
     let swapResult = swap(flawedIndex,numbers);

     //if the swapresult is true, then return that it is ascending
     if (swapResult == true) return true;   }
      //else return that its false   return false; }

 const swap = (flawIndex, numbers) => {
      let num = numbers[flawIndex];
      //convert the given array el to a string, and split the string based on ''   let numToString = num.toString().split('');

 //iterate through every digit from index 0   for(let i=0;
 i<numToString.length; i++) {

     //iterate from every digit from index 1
     for(let j=i+1; j<numToString.length; j++) {

       //swap the first index digit with every other index digit
       let temp = numToString[i];
       numToString[i] = numToString[j]
       numToString[j] = temp;

       console.log(numToString)

       //check if the swapped number is lesser than the next number in the main array
       //AND if it is greater than the previous el in the array. if yes, return true
       let swappedNum = Number(numToString.join(''));
       if(swappedNum < numbers[flawIndex + 1] && swappedNum > numbers[flawIndex-])
   {
         return true;
       }

     }   }   //else return false   return false; }
</code>```

console.log("the solution is ",solution([1, 3, 900, 10]))

Title: How to swap digits in number?

Body:
I need to write function that gets 3 params(int num, int k, int nDigit).
The function get number and replace the digit inside the number in k index by nDigit.

for example:

 int num  = 5498
 int k  = 2
 int nDigit= 3

the result is num = 5398

My question is how can I implement it?I undastand that the best way to convert the num to string and then just replace char on specific index by nDigit char.

But is there any way to implement it?Without

Body:
This is my javascript solution.

 const solution = numbers => {   //declare a variable that will hold
the array el that is not strictly ascending   let flawedIndex;
      //declare a boolean variable to actually check if there is a flawed array el in the given array   let flawed = false;
      //iterate through the given array   for(let i=0; i<numbers.length; i++) {

     //check if current array el is greater than the next
     if(numbers[i] > numbers[i+1])
       {
         //check if we already set flawed to true once.
         //if flawed==true, then return that this array cannot be sorted
         //strictly ascending even if we swap one elements digits

         if(flawed) {

           return false;
         }

         //if flawed is false, then set it to true and store the index of the flawed array el
         else {

                            flawed = true;
                        flawedIndex = i;
                                }
       }
        }
      //if flawed is still false after the end of the for loop, return true    //where true = the array is sctrictly ascending   if(flawed ==
 false) return true;
      //if flawed==true, that is there is an array el that is flawed   if(flawed){

     //store the result of calling the swap function on the digits of the flawed array el
     let swapResult = swap(flawedIndex,numbers);

     //if the swapresult is true, then return that it is ascending
     if (swapResult == true) return true;   }
      //else return that its false   return false; }

 const swap = (flawIndex, numbers) => {
      let num = numbers[flawIndex];
      //convert the given array el to a string, and split the string based on ''   let numToString = num.toString().split('');

 //iterate through every digit from index 0   for(let i=0;
 i<numToString.length; i++) {

     //iterate from every digit from index 1
     for(let j=i+1; j<numToString.length; j++) {

       //swap the first index digit with every other index digit
       let temp = numToString[i];
       numToString[i] = numToString[j]
       numToString[j] = temp;

       console.log(numToString)

       //check if the swapped number is lesser than the next number in the main array
       //AND if it is greater than the previous el in the array. if yes, return true
       let swappedNum = Number(numToString.join(''));
       if(swappedNum < numbers[flawIndex + 1] && swappedNum > numbers[flawIndex-])
   {
         return true;
       }

     }   }   //else return false   return false; }

console.log("the solution is ",solution([1, 3, 900, 10]))