问:
How to Convert a Map<String, List<List<String>>> to Map<String, List<String>>
```<code> Map<String, List<String>> map1 = new HashMap<>();
  Map<String, List<String>> map2 = new HashMap<>();
   map1.put("a", Lists.newArrayList("1","123"));
    map1.put("b", Lists.newArrayList("2","223"));

    map2.put("c", Lists.newArrayList("11","1123"));
    map2.put("a", Lists.newArrayList("22","2223"));
  Map<String, List<List<String>>> collect = Stream.of(map1, map2)
            .flatMap(m -> m.entrySet().stream())
            .collect(Collectors.groupingBy(Map.Entry::getKey,
                    Collectors.mapping(Map.Entry::getValue,
                            Collectors.toList())
            ));
 System.out.println(collect);
</code>```

print: {a=[[1, 123], [22, 2223, 1, 123]], b=[[2, 223]], c=[[11, 1123]]}

how can print:
{a=[22, 2223, 1, 123], b=[2, 223], c=[11, 1123]}

答:
You may use a simple for loop and do it like this.

```<code>List<Map<String, List<String>>> source = Arrays.asList(map1, map2);
for (Map<String, List<String>> m : source) {
    for (Map.Entry<String, List<String>> e : m.entrySet()) {
        target.computeIfAbsent(e.getKey(), unused -> new ArrayList<>())
            .addAll(e.getValue());
    }
}
</code>```

A stream based counterpart would be something like this.

```<code>Map<String, List<String>> res = source.stream()
    .flatMap(m -> m.entrySet().stream())
    .collect(Collectors.groupingBy(Map.Entry::getKey,
        Collectors.flatMapping(e -> e.getValue().stream(), Collectors.toList())));
</code>```

The Collectors.flatMapping is available from java9 onwards. If you are using java8, I would recommend you to write your own custom collector for flatMapping and use it here. This will give you an easier migration strategy for Java9 too. You may find an explanation here.

Body:
 Map<String, List<String>> map1 = new HashMap<>();
  Map<String, List<String>> map2 = new HashMap<>();
   map1.put("a", Lists.newArrayList("1","123"));
    map1.put("b", Lists.newArrayList("2","223"));

    map2.put("c", Lists.newArrayList("11","1123"));
    map2.put("a", Lists.newArrayList("22","2223"));
  Map<String, List<List<String>>> collect = Stream.of(map1, map2)
            .flatMap(m -> m.entrySet().stream())
            .collect(Collectors.groupingBy(Map.Entry::getKey,
                    Collectors.mapping(Map.Entry::getValue,
                            Collectors.toList())
            ));
 System.out.println(collect);

print: {a=[[1, 123], [22, 2223, 1, 123]], b=[[2, 223]], c=[[11, 1123]]}

how can print:
{a=[22, 2223, 1, 123], b=[2, 223], c=[11, 1123]}

Body:
You may use a simple for loop and do it like this.

List<Map<String, List<String>>> source = Arrays.asList(map1, map2);
for (Map<String, List<String>> m : source) {
    for (Map.Entry<String, List<String>> e : m.entrySet()) {
        target.computeIfAbsent(e.getKey(), unused -> new ArrayList<>())
            .addAll(e.getValue());
    }
}

A stream based counterpart would be something like this.

Map<String, List<String>> res = source.stream()
    .flatMap(m -> m.entrySet().stream())
    .collect(Collectors.groupingBy(Map.Entry::getKey,
        Collectors.flatMapping(e -> e.getValue().stream(), Collectors.toList())));

The Collectors.flatMapping is available from java9 onwards. If you are using java8, I would recommend you to write your own custom collector for flatMapping and use it here. This will give you an easier migration strategy for Java9 too. You may find an explanation here.


来源: stackexchange

问:
How to abort a stash pop?
I popped a stash and there was a merge conflict. Unlike the question that is listed as a duplicate, I already had some uncommitted changes in the directory which I wanted to keep. I don't just want to make the merge conflict disappear, but also to get my directory back to the state it was before the pop.

I tried git merge --abort, but git claimed no merge was in progress. Is there an easy way to abort a pop without destroying the changes I originally had in the directory?

答:
If you just have the stashed changes try this 1 liner. It removes every local change present.

git checkout -f

ContentLicense: CC BY-SA 4.0

Title: How to abort a stash pop?


问:
Combine index and columns and keep value
I have a DataFrame as below

```<code>    A   B   C
1   1   2   3
2   4   2   5
</code>```

And I want to combine index and column into a new index while keeping the value from the previous column + index as below

```<code>    Value
1A  1
1B  2
1C  3
2A  4
2B  2
2C  5
</code>```

I know I can iterate through it with df.iterrows() and create a new DataFrame from that, but I'm working with a huge dataset and it is too inefficient. Dataset is tens of millions of observations.

答:
Use DataFrame.stack with list comprehension:

```<code>df = df.stack().to_frame('Value')
df.index = [f'{a}{b}' for a, b in df.index]
print (df)
    Value
1A      1
1B      2
1C      3
2A      4
2B      2
2C      5
</code>```

Or use numpy solution with ravel:

```<code>c = np.tile(df.columns, len(df))
i = np.repeat(df.index, len(df.columns))

df = pd.DataFrame({'value': df.to_numpy().ravel()}, index=[f'{a}{b}' for a, b in zip(i, c)])
print (df)
    value
1A      1
1B      2
1C      3
2A      4
2B      2
2C      5
</code>```

Body:
I have a DataFrame as below

    A   B   C
1   1   2   3
2   4   2   5

And I want to combine index and column into a new index while keeping the value from the previous column + index as below

    Value
1A  1
1B  2
1C  3
2A  4
2B  2
2C  5

I know I can iterate through it with df.iterrows() and create a new DataFrame from that, but I'm working with a huge dataset and it is too inefficient. Dataset is tens of millions of observations.

Body:
Use DataFrame.stack with list comprehension:

df = df.stack().to_frame('Value')
df.index = [f'{a}{b}' for a, b in df.index]
print (df)
    Value
1A      1
1B      2
1C      3
2A      4
2B      2
2C      5

Or use numpy solution with ravel:

c = np.tile(df.columns, len(df))
i = np.repeat(df.index, len(df.columns))

df = pd.DataFrame({'value': df.to_numpy().ravel()}, index=[f'{a}{b}' for a, b in zip(i, c)])
print (df)
    value
1A      1
1B      2
1C      3
2A      4
2B      2
2C      5


问:
How Should I Implement Implicit Logouts?
My login system currently works as follows:

Grab the user's username and password from a POST form.

Check the username and salted + hashed password against the database.

If authentication is successful, generate a long, random, alphanumeric string.

Store this string in MySQL, as well as in a $_SESSION variable along with the username.

This is opposed to just putting the user's password in $_SESSION.  I feel like that's leaving the door wide open for spyware to come in and steal the user's credentials.

On each page that requires authentication (e.g. non-sensitive account settings, members-only areas, etc.), check the $_SESSION username and string against those stored in MySQL.

If they match, go ahead and show the page.  Otherwise, show a login form.(?)

When the user explicitly logs out, remove the random strings from MySQL and $_SESSION.

What I'm stuck on is how to handle when the user implicitly logs out.  That is, when he/she closes the browser window without hitting any "log out" button on the site.  I'm pretty sure I still need to remove the random string from MySQL, so someone can't use a stolen cookie to log in afterwards.  But how do I know when the user closes the browser window?

("Remember me" functionality is irrelevant for now.)

答:
How Should I Implement Login Sessions?

Authentication and session management are 2 different things, although they are closely tied together, you seem to be talking about authorization too.

If authentication is successful, generate a long, random, alphanumeric string.

Why? PHP already generates a random identifier (the session id). If you want to differentiate between authenticated/non-authenticated users and/or identify which user owns the current session, just store the username / userid in the session.

putting the user's password in a $_SESSION variable

Why would you ever want to do that - once you've authenticated the user, you never need to use the password again.

check the $_SESSION username and string against those stored in MySQL

Why? How can the session data be changed other than via your code? If you suspect that your serverside code could be tampered with then it doesn't matter what you do, the system will be insecure.

When the user explicitly logs out

...you explicitly destroy the session. That's all.

When you remove the redundancies from your proposition there is no need to clean up after an implicit logout.

BTW: there are a number of security issues you have not addressed in your proposal, notably regenerating the session id after an authentication  attempt.

ContentLicense: CC BY-SA 3.0


问:
[Dart]-what datra type is this list
If I'm to create a list as below,

```<code>      "quizz_answer": [
            {
              "option_id": 1,
              "is_selected": false
            },
            {
              "option_id": 2,
              "is_selected": true
            },
            {
              "option_id": 3,
              "is_selected": true
            },
            {
              "option_id": 4,
              "is_selected": false
            },
        ],
</code>```

can you tell me what data type the list should be

答:
You should create a custom object. Then use a parse json function to manage it.

It’s better if you understand what is object oriented programming.

Title: [Dart]-what datra type is this list

Body:
If I'm to create a list as below,

      "quizz_answer": [
            {
              "option_id": 1,
              "is_selected": false
            },
            {
              "option_id": 2,
              "is_selected": true
            },
            {
              "option_id": 3,
              "is_selected": true
            },
            {
              "option_id": 4,
              "is_selected": false
            },
        ],

can you tell me what data type the list should be


问:
Delaying router pathName until after next-page-transitions is done
I have two separate things going on in a simple setup. I am using the following code:

```<code>className={router.pathname.startsWith("/pagename") ? "menu-active" : ""}
</code>```

to assign the menu-active class to the pagename nav link when we're on the pagename page.

And I am using

```<code>        <PageTransition timeout={450} classNames="page-transition">
      <Component {...pageProps} key={router.route} />
        </PageTransition>
        <style jsx global>{`
          .page-transition-enter {
            opacity: 0;
          }
          .page-transition-enter-active {
            opacity: 1;
            transition: opacity 450ms;
          }
          .page-transition-exit {
            opacity: 1;
          }
          .page-transition-exit-active {
            opacity: 0;
            transition: opacity 450ms;
          }
        `}</style>
</code>```

pretty much verbatim from the next-page-transitions docs page, to have a 450ms fade to white between pages.

Here's the problem. I use menu-active to change the font-style of the active page link to italics, and to change its color to orange. But when you change pages, it seems that the class is applied before the transition happens. In other words, you can see the menu change before the fade out to white even occurs.

I figured I could delay the transition by 450ms and then the change would happen right as the fade was finishing, and that works fine for the color change; but not for the font style. Since font style doesn't work with transition-delay, I am trying to figure out some other way to delay the application of this class/style.

Perhaps I'm going about this all wrong though. Any recommendations?

EDIT: to be clear, I'm in no way married to using next-page-transitions, so feel free to recommend something else for doing what I want to do.

答:
You can try creating two different components, they will be the same but with different font family. by that, you will be able to setTimeout of 450ms for the components to change between them, and this will give you the desired solution.

This is a bit dirty, but atm thats what I managed to think about as adding transition to fonts is problematic.

Will update if any new ideas come to mind

Edit:

I made a small code example for you. i used styled-components, its just like regular css just has different code style, its very easy to convert it to regular css.
And i used react-hooks, for the useState and useEffect. please read about it if you dont understand, its important to know this in order to code in react.

const FontX = styled.p`
  font-family: 'Andale Mono';
`;

const FontY = styled.p`
  font-family: Arial;
`;

const Container = () => {
  const [Component, setComponent] = useState(FontX);

  useEffect(() => {
    setTimeout(() => {
      setComponent(FontY);
    }, 450);
  }, []);

  return <Component>Look here! Font will change after 450ms</Component>;
};```

here sandbox:

https://codesandbox.io/s/strange-yonath-dp4w5?file=/src/App.js

Body:
I have two separate things going on in a simple setup. I am using the following code:

className={router.pathname.startsWith("/pagename") ? "menu-active" : ""}

to assign the menu-active class to the pagename nav link when we're on the pagename page.

And I am using

        <PageTransition timeout={450} classNames="page-transition">
      <Component {...pageProps} key={router.route} />
        </PageTransition>

pretty much verbatim from the next-page-transitions docs page, to have a 450ms fade to white between pages.

Here's the problem. I use menu-active to change the font-style of the active page link to italics, and to change its color to orange. But when you change pages, it seems that the class is applied before the transition happens. In other words, you can see the menu change before the fade out to white even occurs.

I figured I could delay the transition by 450ms and then the change would happen right as the fade was finishing, and that works fine for the color change; but not for the font style. Since font style doesn't work with transition-delay, I am trying to figure out some other way to delay the application of this class/style.

Perhaps I'm going about this all wrong though. Any recommendations?

EDIT: to be clear, I'm in no way married to using next-page-transitions, so feel free to recommend something else for doing what I want to do.

Body:
You can try creating two different components, they will be the same but with different font family. by that, you will be able to setTimeout of 450ms for the components to change between them, and this will give you the desired solution.

This is a bit dirty, but atm thats what I managed to think about as adding transition to fonts is problematic.

Will update if any new ideas come to mind

Edit:

I made a small code example for you. i used styled-components, its just like regular css just has different code style, its very easy to convert it to regular css.
And i used react-hooks, for the useState and useEffect. please read about it if you dont understand, its important to know this in order to code in react.

const FontX = styled.p`
  font-family: 'Andale Mono';
`;

const FontY = styled.p`
  font-family: Arial;
`;

const Container = () => {
  const [Component, setComponent] = useState(FontX);

  useEffect(() => {
    setTimeout(() => {
      setComponent(FontY);
    }, 450);
  }, []);

  return <Component>Look here! Font will change after 450ms</Component>;
};

here sandbox:

https://codesandbox.io/s/strange-yonath-dp4w5?file=/src/App.js


问:
How to connect server to Binance Smart Chain using the Web3.js library?
I'm trying to connect my small server web app in ExpressJS to the BSC blockchain, but without success.

As per my understanding, the Web3 library provides all the required stuff under the hood, and I can connect by calling

new Web3(new Web3.providers.HttpProvider(urlToRpcNode))

By following this, I put the following into my function, which serves as a Web3 object init:

return new Web3(new Web3.providers.HttpProvider(https://bsc-dataseed1.binance.org));

According to BscScan, the given argument is the URL to the RPC Node for BSC https://bscscan.com/apis#rpc.

Unfortunately, awaiting this call just gets stuck forever and doesn't return anything.

What am I doing wrong? Any help is appreciated.

Edit:

I found another link to Binance Docs, where it outlines the specific process for connecting to BSC. Here is how they do it:

const web3 = new Web3('https://bsc-dataseed1.binance.org:443');

https://docs.binance.org/smart-chain/developer/create-wallet.html#connect-to-bsc-network

Unfortunately, this gives me the same result.

答:
Few months later, I remembered asking this. I ended up using an external RPC node provider (fe. QuickNode, Ankr, Infura).

I don't have my exact code on hand, but I know that the steps were as follows:

Open an account on a platform which offers RPC services

Eg. Infura, Ankr, QuickNode (these were the ones that I found)

These services will let you create your own node for a certain blockchain (I saw Eth, Bsc, Polygon, AvalancheC and many others)

After you create your own node, which is of course, paid service, you get an HTTP link for your node, which looks something like this https://mynode2241235.ankr.com/, let's call that LINK from now.

Back on my server, I took the regular Web3 connection code snippet and just modified it by putting this LINK as an HttpProvider, so sth like this:

const instance = new Web3(new Web3.providers.HttpProvider(LINK));


问:
Plotting in widget on ui with PySide6
I need to plot on the predefined part of the ui with PySide6.
The ui is designed with Qt Creator and it contains a widget called "widgetGraph". If I'm using the following example it works, but due to the set of the central widget everything on the ui gets overwritten

```<code>self.ui.widgetGraph = pyqtgraph.PlotWidget()
self.ui.setCentralWidget(self.ui.widgetGraph)

hour = [1,2,3,4,5,6,7,8,9,10]
temperature = [30,32,34,32,33,31,29,32,35,45]

# plot data: x, y values
self.ui.widgetGraph.plot(hour, temperature)
</code>```

Without using the "setCentralWidget" function the widget remains empty.
Is there any way not to override the ui elements, just plot into the previously mentioned "widgetGraph" widget?

答:
As stated in the answer from @musicamante, the plot widget has to added to the layout with the following code:

```<code>self.ui.someLayout.addWidget(self.ui.widgetGraph)
</code>```

Title: Plotting in widget on ui with PySide6

Body:
I need to plot on the predefined part of the ui with PySide6.
The ui is designed with Qt Creator and it contains a widget called "widgetGraph". If I'm using the following example it works, but due to the set of the central widget everything on the ui gets overwritten

self.ui.widgetGraph = pyqtgraph.PlotWidget()
self.ui.setCentralWidget(self.ui.widgetGraph)

hour = [1,2,3,4,5,6,7,8,9,10]
temperature = [30,32,34,32,33,31,29,32,35,45]

# plot data: x, y values
self.ui.widgetGraph.plot(hour, temperature)

Without using the "setCentralWidget" function the widget remains empty.
Is there any way not to override the ui elements, just plot into the previously mentioned "widgetGraph" widget?

Body:
As stated in the answer from @musicamante, the plot widget has to added to the layout with the following code:

self.ui.someLayout.addWidget(self.ui.widgetGraph)


问:
Cannot access API view on post request using decorator [AllowAny]
I have a simple function-based @api_view(['POST']) with @permission_classes([AllowAny])
and DRF settings in settings.py are:

```<code>REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ],
    'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
}
</code>```

The documentation says:

The AllowAny permission class will allow unrestricted access,
regardless of if the request was authenticated or unauthenticated.

But I'm getting the following response on making a post request:

```<code>{
    "detail": "Authentication credentials were not provided."
}
</code>```

What might be the problem? Do I have to modify DEFAULT_AUTHENTICATION_CLASSES from the settings? I don't want the permissions to be required while making the request on this @api_view:

```<code>@api_view(['POST'])
@permission_classes([AllowAny])
def reset_password_request(email):
    try:
    #...
</code>```

accounts/urls.py:

```<code>urlpatterns = [
    path('user/<str:pk>/', views.getUserById, name='user'),
    path('user/password_reset_request/',
         views.resetPasswordRequest, name='password_reset_request'),
]
</code>```

答:
Let's work through it step by step: Add DEFAULT_PERMISSION_CLASSES as follows (for troubleshooting):

```<code>REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
     )
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ],
    'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
}
</code>```

** EDIT 1 **

Try adding rest_framework.authentication.SessionAuthentication as follows:

```<code>REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
     )
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
        'rest_framework.authentication.SessionAuthentication'
    ],
    'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
}
</code>```

** EDIT 2 **

Now that you have a 403, modify the default to rest_framework.permissions.AllowAny as shown below. If this works, remove the DEFAULT_PERMISSION_CLASSES and use decorators instead.

```<code>REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.AllowAny',
     )
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
        'rest_framework.authentication.SessionAuthentication'
    ],
    'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
}
</code>```

Body:
I have a simple function-based @api_view(['POST']) with @permission_classes([AllowAny])
and DRF settings in settings.py are:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ],
    'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
}

The documentation says:

The AllowAny permission class will allow unrestricted access,
regardless of if the request was authenticated or unauthenticated.

But I'm getting the following response on making a post request:

{
    "detail": "Authentication credentials were not provided."
}

What might be the problem? Do I have to modify DEFAULT_AUTHENTICATION_CLASSES from the settings? I don't want the permissions to be required while making the request on this @api_view:

@api_view(['POST'])
@permission_classes([AllowAny])
def reset_password_request(email):
    try:
    #...

accounts/urls.py:

urlpatterns = [
    path('user/<str:pk>/', views.getUserById, name='user'),
    path('user/password_reset_request/',
         views.resetPasswordRequest, name='password_reset_request'),
]

Body:
Let's work through it step by step: Add DEFAULT_PERMISSION_CLASSES as follows (for troubleshooting):

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
     )
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ],
    'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
}

** EDIT 1 **

Try adding rest_framework.authentication.SessionAuthentication as follows:

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
     )
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
        'rest_framework.authentication.SessionAuthentication'
    ],
    'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
}

** EDIT 2 **

Now that you have a 403, modify the default to rest_framework.permissions.AllowAny as shown below. If this works, remove the DEFAULT_PERMISSION_CLASSES and use decorators instead.

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.AllowAny',
     )
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
        'rest_framework.authentication.SessionAuthentication'
    ],
    'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
}


问:
Accessing a Custom Configuration Section in .Net
I am trying to access settings in my config file, which is a series of xml elements listed as such:

```<code><databases>
<database name="DatabaseOne" Value="[value]" />
<database name="DatabaseTwo" Value="[value]" />
</databases>
</code>```

Now I want to access it. I have set up classes like so:

```<code>Public Class DatabaseConfigurationHandler
    Inherits ConfigurationSection

    <ConfigurationProperty("Databases", IsDefaultCollection:=True)> _
   Public ReadOnly Property Databases() As DatabaseCollection
        Get
            Return CType(Me("Databases"), DatabaseCollection)
        End Get
    End Property
End Class

Public Class DatabaseCollection
    Inherits ConfigurationElementCollection

    Protected Overloads Overrides Function CreateNewElement() As ConfigurationElement
        Return (New Database())
    End Function

    Protected Overloads Overrides Function GetElementKey(ByVal element As ConfigurationElement) As Object
        Return (CType(element, Database).DatabaseName)
    End Function

End Class

Public Class Database
    Inherits ConfigurationElement

    <ConfigurationProperty("name", IsKey:=True, IsRequired:=True)> _
       Public Property DatabaseName() As String
        Get
            Return Me("name").ToString()
        End Get
        Set(ByVal Value As String)
            Me("name") = Value
        End Set
    End Property

    <ConfigurationProperty("value", IsRequired:=True)> _
Public Property DatabaseValue() As String
        Get
            Return Me("value").ToString()
        End Get
        Set(ByVal Value As String)
            Me("value") = Value
        End Set
    End Property

End Class
</code>```

I want to be able get the element by it's name and return the value but I can't see to do that:

```<code>Dim config As New DatabaseConfigurationHandler
                config = System.Configuration.ConfigurationManager.GetSection("databases/database")
                Return config.Databases("DatabaseOne")
</code>```

Am I missing some code, what am I doing wrong? Any other errors in the above?

Thanks.

答:
Here's a cut and paste from something very similar I did a few days ago.

Config:

```<code>  <ListConfigurations>
    <lists>
      <add Name="blah" EndpointConfigurationName="blah" ListName="blah" ConnectionString="blah" TableName="blah" FieldsCsv="blah" DbFieldsCsv="blah"/>
      <add Name="blah2" EndpointConfigurationName="blah" ListName="blah" ConnectionString="blah" TableName="blah" FieldsCsv="blah" DbFieldsCsv="blah"/>
    </lists>
  </ListConfigurations>
</code>```

Config section C#:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace App
{
    /// <summary>
    /// Individual list configuration
    /// </summary>
    class ListConfiguration : ConfigurationElement
    {
        [ConfigurationProperty("Name", IsKey = true, IsRequired = true)]
        public string Name
        {
            get { return (string)this["Name"]; }
        }

        [ConfigurationProperty("EndpointConfigurationName", IsRequired = true)]
        public string EndpointConfigurationName
        {
            get { return (string)this["EndpointConfigurationName"]; }
        }

        [ConfigurationProperty("ListName", IsRequired = true)]
        public string ListName
        {
            get { return (string)this["ListName"]; }
        }

        [ConfigurationProperty("ConnectionString", IsRequired = true)]
        public string ConnectionString
        {
            get { return (string)this["ConnectionString"]; }
        }

        [ConfigurationProperty("TableName", IsRequired = true)]
        public string TableName
        {
            get { return (string)this["TableName"]; }
        }

        [ConfigurationProperty("FieldsCsv", IsRequired = true)]
        public string FieldsCsv
        {
            get { return (string)this["FieldsCsv"]; }
        }

        [ConfigurationProperty("DbFieldsCsv", IsRequired = true)]
        public string DbFieldsCsv
        {
            get { return (string)this["DbFieldsCsv"]; }
        }
    }

    /// <summary>
    /// Collection of list configs
    /// </summary>
    class ListConfigurationCollection : ConfigurationElementCollection
    {
        protected override ConfigurationElement CreateNewElement()
        {
            return new ListConfiguration();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((ListConfiguration)element).Name;
        }
    }

    /// <summary>
    /// Config section
    /// </summary>
    class ListConfigurationSection : ConfigurationSection
    {
        [ConfigurationProperty("lists")]
        public ListConfigurationCollection Lists
        {
            get { return (ListConfigurationCollection)this["lists"]; }
        }
    }
}
</code>```

And the code to pick it up from the main app:

```<code>ListConfigurationSection configSection = null;
try
{
    configSection = ConfigurationManager.GetSection("ListConfigurations") as ListConfigurationSection;
}
catch (System.Configuration.ConfigurationErrorsException)
{
}
</code>```

OwnerDisplayName: Damien

ContentLicense: CC BY-SA 2.5

Body:
I am trying to access settings in my config file, which is a series of xml elements listed as such:

<databases>
<database name="DatabaseOne" Value="[value]" />
<database name="DatabaseTwo" Value="[value]" />
</databases>

Now I want to access it. I have set up classes like so:

Public Class DatabaseConfigurationHandler
    Inherits ConfigurationSection

    <ConfigurationProperty("Databases", IsDefaultCollection:=True)> _
   Public ReadOnly Property Databases() As DatabaseCollection
        Get
            Return CType(Me("Databases"), DatabaseCollection)
        End Get
    End Property
End Class

Public Class DatabaseCollection
    Inherits ConfigurationElementCollection

    Protected Overloads Overrides Function CreateNewElement() As ConfigurationElement
        Return (New Database())
    End Function

    Protected Overloads Overrides Function GetElementKey(ByVal element As ConfigurationElement) As Object
        Return (CType(element, Database).DatabaseName)
    End Function

End Class

Public Class Database
    Inherits ConfigurationElement

    <ConfigurationProperty("name", IsKey:=True, IsRequired:=True)> _
       Public Property DatabaseName() As String
        Get
            Return Me("name").ToString()
        End Get
        Set(ByVal Value As String)
            Me("name") = Value
        End Set
    End Property

    <ConfigurationProperty("value", IsRequired:=True)> _
Public Property DatabaseValue() As String
        Get
            Return Me("value").ToString()
        End Get
        Set(ByVal Value As String)
            Me("value") = Value
        End Set
    End Property

End Class

I want to be able get the element by it's name and return the value but I can't see to do that:

Dim config As New DatabaseConfigurationHandler
                config = System.Configuration.ConfigurationManager.GetSection("databases/database")
                Return config.Databases("DatabaseOne")

Am I missing some code, what am I doing wrong? Any other errors in the above?

Thanks.

Body:
Here's a cut and paste from something very similar I did a few days ago.

Config:

  <ListConfigurations>
    <lists>
      <add Name="blah" EndpointConfigurationName="blah" ListName="blah" ConnectionString="blah" TableName="blah" FieldsCsv="blah" DbFieldsCsv="blah"/>
      <add Name="blah2" EndpointConfigurationName="blah" ListName="blah" ConnectionString="blah" TableName="blah" FieldsCsv="blah" DbFieldsCsv="blah"/>
    </lists>
  </ListConfigurations>

Config section C#:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace App
{
    /// <summary>
    /// Individual list configuration
    /// </summary>
    class ListConfiguration : ConfigurationElement
    {
        [ConfigurationProperty("Name", IsKey = true, IsRequired = true)]
        public string Name
        {
            get { return (string)this["Name"]; }
        }

        [ConfigurationProperty("EndpointConfigurationName", IsRequired = true)]
        public string EndpointConfigurationName
        {
            get { return (string)this["EndpointConfigurationName"]; }
        }

        [ConfigurationProperty("ListName", IsRequired = true)]
        public string ListName
        {
            get { return (string)this["ListName"]; }
        }

        [ConfigurationProperty("ConnectionString", IsRequired = true)]
        public string ConnectionString
        {
            get { return (string)this["ConnectionString"]; }
        }

        [ConfigurationProperty("TableName", IsRequired = true)]
        public string TableName
        {
            get { return (string)this["TableName"]; }
        }

        [ConfigurationProperty("FieldsCsv", IsRequired = true)]
        public string FieldsCsv
        {
            get { return (string)this["FieldsCsv"]; }
        }

        [ConfigurationProperty("DbFieldsCsv", IsRequired = true)]
        public string DbFieldsCsv
        {
            get { return (string)this["DbFieldsCsv"]; }
        }
    }

    /// <summary>
    /// Collection of list configs
    /// </summary>
    class ListConfigurationCollection : ConfigurationElementCollection
    {
        protected override ConfigurationElement CreateNewElement()
        {
            return new ListConfiguration();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((ListConfiguration)element).Name;
        }
    }

    /// <summary>
    /// Config section
    /// </summary>
    class ListConfigurationSection : ConfigurationSection
    {
        [ConfigurationProperty("lists")]
        public ListConfigurationCollection Lists
        {
            get { return (ListConfigurationCollection)this["lists"]; }
        }
    }
}

And the code to pick it up from the main app:

ListConfigurationSection configSection = null;
try
{
    configSection = ConfigurationManager.GetSection("ListConfigurations") as ListConfigurationSection;
}
catch (System.Configuration.ConfigurationErrorsException)
{
}

OwnerDisplayName: Steve Robbins


问:
How to use typedef to an array of function pointers
I have an array of function pointer:

```<code>int (*collection[2]) (int input1, int input 2) = {&fct1,&fct2}
</code>```

I can get values by calling both functions from the array:

```<code>*collection[0](1,2);
*collection[1](1,2);
</code>```

Using typedef, I want another way to invoke the array of function pointer. So far, I am doing:

```<code>typedef int (*alternameName)(int input1, int input 2);
alternateName p = &collection[2];
int result1 = (*p[0])(1,2);
int result2 = (*p[1])(1,2);
printf("results are: %d, %d",result1, result2);
</code>```

My issue is I do not think I properly defined the variable p as I keep getting 0 as my results.

答:
It is generally cleaner to typedef function types, not function pointers. It results in cleaner syntax:

```<code>typedef int collection_f(int, int);
</code>```

Now you can define collection, simply as an array of pointer to collection_f.

```<code>collection_f* collection[2] = {&fct1,&fct2};
</code>```

A typical call syntax would be:

```<code>collection[0](1,2);
collection[1](1,2);
</code>```

Don't de-reference function pointer prior to calling. Actually, call operator takes a function pointer as an operand, not a function. Functions decay to function pointer in all context except & operator ... which returns a function pointer.

Next, I'm not sure what:

```<code>alternateName p = &collection[2];
</code>```

is supposed to mean. I assume that you want p to point to the first element of collection. Moreover, indexing p[1] and p[2] looks like out of bound access because accessing collection is only defined for indices 0 and 1.

Now your code could be rewritten can:

```<code>collection_f** p = collection; // pointer to first element which is a pointer to collection_f
int result1 = p[0](1,2);
int result2 = p[1](1,2);
printf("results are: %d, %d",result1, result2);
</code>```

I hope it fixes the problem.

Body:
I have an array of function pointer:

int (*collection[2]) (int input1, int input 2) = {&fct1,&fct2}

I can get values by calling both functions from the array:

*collection[0](1,2);
*collection[1](1,2);

Using typedef, I want another way to invoke the array of function pointer. So far, I am doing:

typedef int (*alternameName)(int input1, int input 2);
alternateName p = &collection[2];
int result1 = (*p[0])(1,2);
int result2 = (*p[1])(1,2);
printf("results are: %d, %d",result1, result2);

My issue is I do not think I properly defined the variable p as I keep getting 0 as my results.

Body:
It is generally cleaner to typedef function types, not function pointers. It results in cleaner syntax:

typedef int collection_f(int, int);

Now you can define collection, simply as an array of pointer to collection_f.

collection_f* collection[2] = {&fct1,&fct2};

A typical call syntax would be:

collection[0](1,2);
collection[1](1,2);

Don't de-reference function pointer prior to calling. Actually, call operator takes a function pointer as an operand, not a function. Functions decay to function pointer in all context except & operator ... which returns a function pointer.

Next, I'm not sure what:

alternateName p = &collection[2];

is supposed to mean. I assume that you want p to point to the first element of collection. Moreover, indexing p[1] and p[2] looks like out of bound access because accessing collection is only defined for indices 0 and 1.

Now your code could be rewritten can:

collection_f** p = collection; // pointer to first element which is a pointer to collection_f
int result1 = p[0](1,2);
int result2 = p[1](1,2);
printf("results are: %d, %d",result1, result2);

I hope it fixes the problem.


问:
Visual Studio Code extensions stopped working suddenly
I'm having problem with my Visual Studio Code. Yesterday I had my pc shut down with VS Code open, and when I turned pc on again, all VS Code extensions stopped working. I'm using React and Typescript in my project and I really need those extensions. My eslint and prettier configurations also stopped working.
If somebody had the same problem please answer.</p>

答:
I had that problem on WSL (Windows Subsystem for Linux). The error was like this:

```<code>/mnt/c/Users/Admin/.vscode/extensions/ms-vscode-remote.remote-wsl-0.63.13/scripts/wslCode.sh: 69: /home/raul/.vscode-server-server/bin/5554b12acf27056905806867f251c859323ff7e9/bin/code: not found
</code>```

The solution was to go to Windows PowerShell and open Visual Studio Code, then go to the extensions and restart the Remote - WSL extension, and go back to WSL. It then started working immediately.

Body:
I had that problem on WSL (Windows Subsystem for Linux). The error was like this:

/mnt/c/Users/Admin/.vscode/extensions/ms-vscode-remote.remote-wsl-0.63.13/scripts/wslCode.sh: 69: /home/raul/.vscode-server-server/bin/5554b12acf27056905806867f251c859323ff7e9/bin/code: not found

The solution was to go to Windows PowerShell and open Visual Studio Code, then go to the extensions and restart the Remote - WSL extension, and go back to WSL. It then started working immediately.


问:
How to secure account balance in firebase?
My first question here. I'd like to use Stripe as payment gateway in my ionic app. And update the balance in firebase after charging the user.

However, I'm not sure about how should I write the rule to secure the balance from re-writting by user. How should I write the rule?

My users stored as something like this

```<code>{
    users
    {
        'nciwhjd7832hjkscdsd' {
            userName: 'Tom'
            balance: 20
        }
    }
}
</code>```

答:
You should combine the firebase [rules][1] with writing your data as [transactions][2]</p>
```<code>"users": {
  ".read": "auth != null",
  "$uid": {
      ".validate": "newData.isNumber() && newData.val() >= 0",
      ".write": "auth != null && auth.uid == $uid"
    }
}
</code>```

Body:
My first question here. I'd like to use Stripe as payment gateway in my ionic app. And update the balance in firebase after charging the user.

However, I'm not sure about how should I write the rule to secure the balance from re-writting by user. How should I write the rule?

My users stored as something like this

{
    users
    {
        'nciwhjd7832hjkscdsd' {
            userName: 'Tom'
            balance: 20
        }
    }
}

Body:
You should combine the firebase [rules][1] with writing your data as [transactions][2]

"users": {
  ".read": "auth != null",
  "$uid": {
      ".validate": "newData.isNumber() && newData.val() >= 0",
      ".write": "auth != null && auth.uid == $uid"
    }
}


问:
What page builds first?
I need to call getStaticProps method on a build before other pages will start building. So is there any way to set what page needs to build first or set getStaticProps method somewhere before pages will build?

My goal is to create a file on build and update it with 'revalidate' option. An that needs to be done before other pages will build

答:
Before I answer your question, I want to note that, the calls in the getStatic props are evaluated on build time, as a result not affected when a user visits the page, therefore, as long as you do not rebuild the application, the total calls that will happen is just 10. When a user visits the page, it will not make the getStaticProps again.

From this article you may have to modify your configurations to allow that.

Now lets look at some ways you can achieve what you are saying.

A pre build hook.

This can be done outside of the next basically, you can add your code to a  file lets say script.js and add a prebuild hook which should run before you build. you can specify this hook in your package.json.
PS. This might not run on revalidateYou might need further investigation

```<code>  "prebuild": "node script.js",
  "build": "next build",
  "start": "next start",
</code>```

in the ./pages/_app.js file.

You can modify the get static props in the app.js file. You only do this if you do not need the automatic static page generation. ie, you should explicitly state that the page should be statically generated in subsequent pages by adding a getStaticProps. You can find out more here. And I will add a quote from there.

Only uncomment this method if you have blocking data requirements for
every single page in your application. This disables the ability to
perform automatic static optimization, causing every page in your app
to be server-side rendered.

```<code>import App from 'next/app'

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

MyApp.getInitialProps = async (appContext) => {
  // you can put your file stuff here
  const appProps = await App.getInitialProps(appContext);

  return { ...appProps }
}

export default MyApp
</code>```

Let me know how it goes in the comment, i will gladly help out more if i can.

Title: What page builds first?

Body:
Before I answer your question, I want to note that, the calls in the getStatic props are evaluated on build time, as a result not affected when a user visits the page, therefore, as long as you do not rebuild the application, the total calls that will happen is just 10. When a user visits the page, it will not make the getStaticProps again.

From this article you may have to modify your configurations to allow that.

Now lets look at some ways you can achieve what you are saying.

A pre build hook.

This can be done outside of the next basically, you can add your code to a  file lets say script.js and add a prebuild hook which should run before you build. you can specify this hook in your package.json.
PS. This might not run on revalidateYou might need further investigation

  "prebuild": "node script.js",
  "build": "next build",
  "start": "next start",

in the ./pages/_app.js file.

You can modify the get static props in the app.js file. You only do this if you do not need the automatic static page generation. ie, you should explicitly state that the page should be statically generated in subsequent pages by adding a getStaticProps. You can find out more here. And I will add a quote from there.

Only uncomment this method if you have blocking data requirements for
every single page in your application. This disables the ability to
perform automatic static optimization, causing every page in your app
to be server-side rendered.

import App from 'next/app'

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

MyApp.getInitialProps = async (appContext) => {
  // you can put your file stuff here
  const appProps = await App.getInitialProps(appContext);

  return { ...appProps }
}

export default MyApp

Let me know how it goes in the comment, i will gladly help out more if i can.


问:
Does drawRect: automatically check whether something is within the bounds of the CGRect passed to it?
I'm wondering whether I need to check if something is within the bounds of the CGRect passed to drawRect:, or if drawRect: automatically handles that for me.

For example, assume that I have 10 UIBezierPaths on the screen. Each curve is in an NSMutableArray named curves. Every time drawRect: is called, it loops through this array and draws the curves it finds there. If the use moves one curve, I find its containing CGRect and call [self setNeedsDisplayInRect:containingRect]. In my drawRect: implementation, do I need to personally check whether each of the UIBezierPaths falls within the CGRect passed to drawRect: (using CGRectIntersectsRect), or is that handled automatically?

答:
This falls into a class of optimizations you'll have to make yourself if you think it's necessary after profiling.

UIKit isn't that smart unfortunately. Though it would probably be too slow if it was!


问:
golang git pulling a repo
I'm very new to golang
Im trying to do a git pull from go program. I have looked in to native libraries and found https://github.com/src-d/go-git/.

I has features to of cloning ect. but not pulling. Looking at the source it seems there is a function for pulling as well

```<code>func (r *Repository) Pull(o *PullOptions)
</code>```

However compiler warns that its undefined. Can anyone point me how can I do this or to an alternative library which supports both clone and pull ?

答:
gopkg.in/src-d/go-git.v4 is no longer maintained recommended to use github.com/go-git/go-git instead. Refer - https://pkg.go.dev/github.com/go-git/go-git

Sample code

```<code>import "github.com/go-git/go-git/v5"

_, err := git.PlainClone("/tmp/foo", false, &git.CloneOptions{
    URL:      "https://github.com/go-git/go-git",
    Progress: os.Stdout,
})
</code>```

Title: golang git pulling a repo

Body:
I'm very new to golang
Im trying to do a git pull from go program. I have looked in to native libraries and found https://github.com/src-d/go-git/.

I has features to of cloning ect. but not pulling. Looking at the source it seems there is a function for pulling as well

func (r *Repository) Pull(o *PullOptions)

However compiler warns that its undefined. Can anyone point me how can I do this or to an alternative library which supports both clone and pull ?

Body:
gopkg.in/src-d/go-git.v4 is no longer maintained recommended to use github.com/go-git/go-git instead. Refer - https://pkg.go.dev/github.com/go-git/go-git

Sample code

import "github.com/go-git/go-git/v5"

_, err := git.PlainClone("/tmp/foo", false, &git.CloneOptions{
    URL:      "https://github.com/go-git/go-git",
    Progress: os.Stdout,
})


问:
How to override CSS styles of Bootstrap for ".navlink"?
I'm not able to change the color of the ".navlink" to white in my html file.
Please help me to change the color of the ".navlink" to white.

       tent workshop
       <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

       </button>

                   Home

                   Contact

                   Products

```

答:
would you try this?

```<code><a href="#" class="nav-link" style="color:white;" aria-current="page">Home</a>
</code>```

style="color:white;" it usually works

Body:
would you try this?

<a href="#" class="nav-link" style="color:white;" aria-current="page">Home</a>

style="color:white;" it usually works


问:
Scala Compiliation error with intellij
I'm trying to compile a mixed java-scala code using intelliJ 14.1.4

but it keeps giving me this error:

```<code>Error Compiling SBT component 'compiler-interface-2.9.2-52.0'
</code>```

I have tried to down grade my scala-compiler version but this didn't helped.

any help would be appreciated.

答:
To add to Amy's and other answers, there are three places where JDK is involved. The first two are in the Project Settings, the third is
Settings -> Build, Execution, Deployment -> Compiler -> Scala Compiler -> Scala Compile Server (if enabled).
If this problem arises, check these three are the same.</p>

Title: Scala Compiliation error with intellij

Body:
I'm trying to compile a mixed java-scala code using intelliJ 14.1.4

but it keeps giving me this error:

Error Compiling SBT component 'compiler-interface-2.9.2-52.0'

I have tried to down grade my scala-compiler version but this didn't helped.

any help would be appreciated.


问:
What is the difference between sudo pip3 install pygame and sudo apt install python3-pygame
At first I entered the command sudo pip3 install pygame in order to install pygame but then when I entered sudo apt install python3-pygame, It did not prompt me saying that it was already installed. What is the difference?

答: apt is for linux. pip is for python</p>

Body: apt is for linux. pip is for python


问:
Powershell: Convert get-adpermission object to get-aduser object
I'm trying to run a report of users with Send-As rights to mailboxes. I'm using the following code which is working fine:

```<code>$sa_user = Get-Mailbox -id <mailbox> | Get-ADPermission | where { ($_.ExtendedRights -like "*Send-As*") -and ($_.IsInherited -eq $false) }
</code>```

But the ${sa_user.User} data can be rather "unhelpful" and I've been asked to provide more useful data (namingly: Department, CanonicalName, and DisplayName).

I'd like to tie the $sa_user adpermission object to an aduser object, as it has all those properties I need for the report. I've tried:

```<code>$ad_user = Get-ADUser -id $sa_user.identity
</code>```

But $sa_user.identity is for the mailbox, not the user. So I tried:

```<code>$ad_user = Get-ADUser -id $sa_user.User
</code>```

But I get only errors that Get-ADUser cmdlet Identify can't find the value given by $sa_user.User.

So my question is; How do I get the aduser object based off available properties from the adpermission object?...Or any other way or shortcut or intermediary to get there?

答:
Try

```<code>$ad_user = Get-ADUser -Filter * -Properties msDS-PrincipalName | where-object {$_.'msDS-PrincipalName' -eq $sa_user.User}
</code>```

OR

```<code>$ad_user = Get-ADUser -Filter * -Properties sAMAccountName | where-object {$_.sAMAccountName -eq ($sa_user.User -replace ".+\\")}
</code>```

.

Edit 01.12.2022

After I noticed that filtering that way could be possible very slow I tried something different. Here is the whole code to loop trought send-as authorized users/objects. You only have to define a searchbase:

```<code>function Convert-CN2DN([string]$cn) {
    $obj = $cn.Split('/')
    if(-not $obj[0].Contains('.')) {
        $cn
    } else {
        [string]$DN = 'CN=' + $obj[$obj.count - 1]
        for ($i = $obj.count - 2; $i -ge 1; $i--) { $DN += ',OU=' + $obj[$i] }
        $obj[0].split('.') | ForEach-Object { $DN += ',DC=' + $_ }
        $DN
    }
}

$user_NTAUTHORITY = "NT AUTHORITY" # This is language specific. For example in german: "NT-AUTORITÄT"
$Searchbase = "" # <--- define a searchbase

$MailBoxes = Get-Mailbox -OrganizationalUnit $Searchbase
foreach($Mailbox in $MailBoxes) {
    $RecipientPermissions = $Mailbox | Get-RecipientPermission | ? { -not ($_.Trustee -match $user_NTAUTHORITY) -and ($_.IsInherited -eq $false)}
    foreach($RecipientPermission in $RecipientPermissions) {
        if($RecipientPermission.Trustee) {

            $MailboxUser = Get-ADUser -Identity $Mailbox.DistinguishedName -Properties description,msExchResourceDisplay | Select ObjectClass,msExchResourceDisplay,description,Name

            $SendAsObject_DN = Convert-CN2DN $RecipientPermission.Trustee
            if($SendAsObject_DN -ne $RecipientPermission.Trustee) { # When converting was successful. (Just in case of deleted users.)
                $SendAsObject = Get-ADObject -Identity $SendAsObject_DN -properties mail | Select Name,ObjectClass,distinguishedName,mail
            } else {
                $SendAsObject = ""
            }

            # Now you could work with
            # $MailboxUser
            # $SendAsObject
        }
    }
}
</code>```

Body:
I'm trying to run a report of users with Send-As rights to mailboxes. I'm using the following code which is working fine:

$sa_user = Get-Mailbox -id <mailbox> | Get-ADPermission | where { ($_.ExtendedRights -like "*Send-As*") -and ($_.IsInherited -eq $false) }

But the ${sa_user.User} data can be rather "unhelpful" and I've been asked to provide more useful data (namingly: Department, CanonicalName, and DisplayName).

I'd like to tie the $sa_user adpermission object to an aduser object, as it has all those properties I need for the report. I've tried:

$ad_user = Get-ADUser -id $sa_user.identity

But $sa_user.identity is for the mailbox, not the user. So I tried:

$ad_user = Get-ADUser -id $sa_user.User

But I get only errors that Get-ADUser cmdlet Identify can't find the value given by $sa_user.User.

So my question is; How do I get the aduser object based off available properties from the adpermission object?...Or any other way or shortcut or intermediary to get there?

Body:
Try

$ad_user = Get-ADUser -Filter * -Properties msDS-PrincipalName | where-object {$_.'msDS-PrincipalName' -eq $sa_user.User}

OR

$ad_user = Get-ADUser -Filter * -Properties sAMAccountName | where-object {$_.sAMAccountName -eq ($sa_user.User -replace ".+\\")}

.

Edit 01.12.2022

After I noticed that filtering that way could be possible very slow I tried something different. Here is the whole code to loop trought send-as authorized users/objects. You only have to define a searchbase:

function Convert-CN2DN([string]$cn) {
    $obj = $cn.Split('/')
    if(-not $obj[0].Contains('.')) {
        $cn
    } else {
        [string]$DN = 'CN=' + $obj[$obj.count - 1]
        for ($i = $obj.count - 2; $i -ge 1; $i--) { $DN += ',OU=' + $obj[$i] }
        $obj[0].split('.') | ForEach-Object { $DN += ',DC=' + $_ }
        $DN
    }
}

$user_NTAUTHORITY = "NT AUTHORITY" # This is language specific. For example in german: "NT-AUTORITÄT"
$Searchbase = "" # <--- define a searchbase

$MailBoxes = Get-Mailbox -OrganizationalUnit $Searchbase
foreach($Mailbox in $MailBoxes) {
    $RecipientPermissions = $Mailbox | Get-RecipientPermission | ? { -not ($_.Trustee -match $user_NTAUTHORITY) -and ($_.IsInherited -eq $false)}
    foreach($RecipientPermission in $RecipientPermissions) {
        if($RecipientPermission.Trustee) {

            $MailboxUser = Get-ADUser -Identity $Mailbox.DistinguishedName -Properties description,msExchResourceDisplay | Select ObjectClass,msExchResourceDisplay,description,Name

            $SendAsObject_DN = Convert-CN2DN $RecipientPermission.Trustee
            if($SendAsObject_DN -ne $RecipientPermission.Trustee) { # When converting was successful. (Just in case of deleted users.)
                $SendAsObject = Get-ADObject -Identity $SendAsObject_DN -properties mail | Select Name,ObjectClass,distinguishedName,mail
            } else {
                $SendAsObject = ""
            }

            # Now you could work with
            # $MailboxUser
            # $SendAsObject
        }
    }
}


问:
I tried everything but it's show this error in React-Native
I Just Started Learning React Native after I completed my react js and this error show every time I create new React-Native Project and I loose hope to learn React-Native</p>
```<code>error Failed to install the app. Make sure you have the Android development environment
set up: https://reactnative.dev/docs/environment-setup.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081
Warning: Mapping new ns http://schemas.android.com/repository/android/common/02 to old ns http://schemas.android.com/repository/android/common/01
Warning: Mapping new ns http://schemas.android.com/repository/android/generic/02 to old ns http://schemas.android.com/repository/android/generic/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/addon2/02 to old ns http://schemas.android.com/sdk/android/repo/addon2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/repository2/02 to old ns http://schemas.android.com/sdk/android/repo/repository2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/sys-img2/02 to old ns http://schemas.android.com/sdk/android/repo/sys-img2/01
Warning: Mapping new ns http://schemas.android.com/repository/android/common/02 to old ns http://schemas.android.com/repository/android/common/01
Warning: Mapping new ns http://schemas.android.com/repository/android/generic/02 to old ns http://schemas.android.com/repository/android/generic/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/addon2/02 to old ns http://schemas.android.com/sdk/android/repo/addon2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/repository2/02 to old ns http://schemas.android.com/sdk/android/repo/repository2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/sys-img2/02 to old ns http://schemas.android.com/sdk/android/repo/sys-img2/01

FAILURE: Build failed with an exception.

  * What went wrong:
    Execution failed for task ':app:processDebugMainManifest'.
    > Unable to make field private final java.lang.String java.io.File.path accessible: module java.base does not "opens java.io" to unnamed module @36838899

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

  * Get more help at https://help.gradle.org

 BUILD FAILED in 12s

at makeError (D:\React-Native\React Native Cli\AwesomeProject\node_modules\execa\index.js:174:9)
at D:\React-Native\React Native Cli\AwesomeProject\node_modules\execa\index.js:278:16
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async runOnAllDevices (D:\React-Native\React Native Cli\AwesomeProject\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:109:5)
at async Command.handleAction (D:\React-Native\React Native Cli\AwesomeProject\node_modules\@react-native-community\cli\build\index.js:192:9)## Heading ##
</code>```

答:
If you get the error message while running react-native run-android, try to go to android folder and clean gradlew cd android && ./gradlew clean
Also you can trying run chmod +x gradlew

Your project should be successfully started

Or visit here

Body:
I Just Started Learning React Native after I completed my react js and this error show every time I create new React-Native Project and I loose hope to learn React-Native

error Failed to install the app. Make sure you have the Android development environment
set up: https://reactnative.dev/docs/environment-setup.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081
Warning: Mapping new ns http://schemas.android.com/repository/android/common/02 to old ns http://schemas.android.com/repository/android/common/01
Warning: Mapping new ns http://schemas.android.com/repository/android/generic/02 to old ns http://schemas.android.com/repository/android/generic/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/addon2/02 to old ns http://schemas.android.com/sdk/android/repo/addon2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/repository2/02 to old ns http://schemas.android.com/sdk/android/repo/repository2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/sys-img2/02 to old ns http://schemas.android.com/sdk/android/repo/sys-img2/01
Warning: Mapping new ns http://schemas.android.com/repository/android/common/02 to old ns http://schemas.android.com/repository/android/common/01
Warning: Mapping new ns http://schemas.android.com/repository/android/generic/02 to old ns http://schemas.android.com/repository/android/generic/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/addon2/02 to old ns http://schemas.android.com/sdk/android/repo/addon2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/repository2/02 to old ns http://schemas.android.com/sdk/android/repo/repository2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/sys-img2/02 to old ns http://schemas.android.com/sdk/android/repo/sys-img2/01

FAILURE: Build failed with an exception.

  * What went wrong:
    Execution failed for task ':app:processDebugMainManifest'.
    > Unable to make field private final java.lang.String java.io.File.path accessible: module java.base does not "opens java.io" to unnamed module @36838899

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

  * Get more help at https://help.gradle.org

 BUILD FAILED in 12s

at makeError (D:\React-Native\React Native Cli\AwesomeProject\node_modules\execa\index.js:174:9)
at D:\React-Native\React Native Cli\AwesomeProject\node_modules\execa\index.js:278:16
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async runOnAllDevices (D:\React-Native\React Native Cli\AwesomeProject\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:109:5)
at async Command.handleAction (D:\React-Native\React Native Cli\AwesomeProject\node_modules\@react-native-community\cli\build\index.js:192:9)## Heading ##


问:
How do I store database sessions in CodeIgniter with multiple databases?
I am using codeigniter and till date I was using cookie based sessions.. but now size of sessions is increased so i need to store them in database..

I have multiple database(more than 3) connected to  my application..How can i specifically use ci_sessions table to store sessions?

when i say $config['sess_use_database']    = TRUE; my app goes blank. a plane white page is shown.

That is because From multiple database connections codeigniter is not finding exact database to store sessions..

How can i achieve the same?
Thanks

答:
Looking at the session code from system/libraries/Session.php, one can see that it uses the default $this->db to connect to the database for storing sessions.

Try modifying your database groups such that $this->db works. Alternatively, you can extend the Session.php such that you can pass it the database group for storing sessions.

Hope this gets you started in the right direction.


问:
How to use a NextJS app with an existing Node.js backend?
Currently I have an existing Node.js backend that works with my create-react-app project.

I'm migrating to NextJS but have some questions.

I have a simple JWT authentication process:

frontend makes request to my-server/api/auth

backend authenticates user, adds refresh token as httpOnly cookie to response header. and returns access token as response body.

Every next call to server will include the access token and refresh token in cookies.

My quesetion is if my NextJS app which is deployed to vercel with domain: www.my-nextjs-app.vercel.com, is making requests to my backend app which is deployed to aws at www.my-backend-app.aws.com, then the cookies my backend set won't be applied because of CORS (since they considered third party cookies from different domain).

(That's also true if I locally server my create-react-app at localhost:3000 and make requests to my local server at localhost:5000, chrome won't show the httpOnly cookie because it's from a different domain)

This is different from my create-react-app which was served directly from my backend at the same domain and thus had no problem of third party cookies.

Is there a solution for that?

Edit: Also, is Next.JS really meant to be used with an existing server? or serverless only

答:
Using multiple servers for ui and backend is pretty common. There are several ways to solve your issue:

1.Deploy everything on one domain and set up reverse proxy (the image is taken from here )

Ofcourse those orging servers can be different apps on the machine running on different ports. You could use nginx as a reverse proxy the config would look like this:

```<code>server {
    listen      80;
    server_name yourapp.com;

    location / {
       proxy_set_header Host $host;
       proxy_set_header X-Real-IP $remote_addr;
       proxy_pass http://uiapp.com:3000;
    }

    location /backend/ {
       rewrite ^/backend(/.*)$ $1 break;
       proxy_set_header Host $host;
       proxy_set_header X-Real-IP $remote_addr;
       proxy_pass http://backendapp.com:8000;
    }
}
</code>```

The rewrite directive is required if you'd like to proxy requests from http://yourapp.com/backend/foobar to http://backendapp.com:8000/foobar

More details on how to set up nginx is here. But there are lots of other guied on the internet.

You can also use middleware for your existing node.js app to proxypass to your NextJs app.

2.Deploy your backend server on subdomain. If you specify Domain for http-only cookies they will be send to subdomains as well. E.g. if use yourapp.com as a domain the cookie will be available on backend.yourapp.com and yourapp.com

```<code>Set-Cookie: name=value; domain=yourapp.com
</code>```

3.Use Authorizatin header instead of cookies. In this case you'll need to send tokens to the UI app and it'll store them either in cookies, sesionStorage or localStorage and you UI app will add Authorization header with your token for your backend:

```<code>var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
xhr.setRequestHeader('Authorization', 'Bearer ' + token);
return xhr;
</code>```

Ofcourse in this case your backend needs to be able to accept token in Authorization header.

Body:
Using multiple servers for ui and backend is pretty common. There are several ways to solve your issue:

1.Deploy everything on one domain and set up reverse proxy (the image is taken from here )

Ofcourse those orging servers can be different apps on the machine running on different ports. You could use nginx as a reverse proxy the config would look like this:

server {
    listen      80;
    server_name yourapp.com;

    location / {
       proxy_set_header Host $host;
       proxy_set_header X-Real-IP $remote_addr;
       proxy_pass http://uiapp.com:3000;
    }

    location /backend/ {
       rewrite ^/backend(/.*)$ $1 break;
       proxy_set_header Host $host;
       proxy_set_header X-Real-IP $remote_addr;
       proxy_pass http://backendapp.com:8000;
    }
}

The rewrite directive is required if you'd like to proxy requests from http://yourapp.com/backend/foobar to http://backendapp.com:8000/foobar

More details on how to set up nginx is here. But there are lots of other guied on the internet.

You can also use middleware for your existing node.js app to proxypass to your NextJs app.

2.Deploy your backend server on subdomain. If you specify Domain for http-only cookies they will be send to subdomains as well. E.g. if use yourapp.com as a domain the cookie will be available on backend.yourapp.com and yourapp.com

Set-Cookie: name=value; domain=yourapp.com

3.Use Authorizatin header instead of cookies. In this case you'll need to send tokens to the UI app and it'll store them either in cookies, sesionStorage or localStorage and you UI app will add Authorization header with your token for your backend:

var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
xhr.setRequestHeader('Authorization', 'Bearer ' + token);
return xhr;

Ofcourse in this case your backend needs to be able to accept token in Authorization header.


问:
"protoc: not found" on an Alpine-based Docker container running Protocol Buffers
I'm trying to build a simple container which downloads a Protocol Buffers binary from the release page (https://github.com/protocolbuffers/protobuf/releases/tag/v3.13.0) and adds it to the path. Following the Linux instructions at http://google.github.io/proto-lens/installing-protoc.html, I've attempted the following Dockerfile:

```<code>FROM golang:alpine

# Install protoc (cf. http://google.github.io/proto-lens/installing-protoc.html)
RUN apk add curl
ENV PROTOC_ZIP=protoc-3.13.0-linux-x86_64.zip
RUN curl -OL https://github.com/protocolbuffers/protobuf/releases/download/v3.13.0/$PROTOC_ZIP \
    && unzip -o $PROTOC_ZIP -d /usr/local bin/protoc \
    && unzip -o $PROTOC_ZIP -d /usr/local 'include/*' \
    && rm -f $PROTOC_ZIP
</code>```

The problem is that if I build it using

```<code>docker build --tag docker-protoc .
</code>```

and run a shell in it, I get a protoc: not found error, even though the binary is in /usr/local/bin which is in the PATH:

```<code>> docker run -it docker-protoc /bin/ash
/go # protoc
/bin/ash: protoc: not found
/go # ls /usr/local/bin
protoc
/go # echo $PATH
/go/bin:/usr/local/go/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
/go #
</code>```

It also occurred to me that I might have downloaded a version of protoc that is not runnable on Alpine Linux, but the linux-x86_64 suffix seems to match the architecture of the container:

```<code>/go # uname -m
x86_64
</code>```

Any idea why protoc can't be executed in this container?

答:
Nowadays you will be fine with just a standard package:

FROM golang:alpine

RUN apk update && apk add --no-cache make protobuf-dev
```

Body:
I'm trying to build a simple container which downloads a Protocol Buffers binary from the release page (https://github.com/protocolbuffers/protobuf/releases/tag/v3.13.0) and adds it to the path. Following the Linux instructions at http://google.github.io/proto-lens/installing-protoc.html, I've attempted the following Dockerfile:

FROM golang:alpine

# Install protoc (cf. http://google.github.io/proto-lens/installing-protoc.html)
RUN apk add curl
ENV PROTOC_ZIP=protoc-3.13.0-linux-x86_64.zip
RUN curl -OL https://github.com/protocolbuffers/protobuf/releases/download/v3.13.0/$PROTOC_ZIP \
    && unzip -o $PROTOC_ZIP -d /usr/local bin/protoc \
    && unzip -o $PROTOC_ZIP -d /usr/local 'include/*' \
    && rm -f $PROTOC_ZIP

The problem is that if I build it using

docker build --tag docker-protoc .

and run a shell in it, I get a protoc: not found error, even though the binary is in /usr/local/bin which is in the PATH:

> docker run -it docker-protoc /bin/ash
/go # protoc
/bin/ash: protoc: not found
/go # ls /usr/local/bin
protoc
/go # echo $PATH
/go/bin:/usr/local/go/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
/go #

It also occurred to me that I might have downloaded a version of protoc that is not runnable on Alpine Linux, but the linux-x86_64 suffix seems to match the architecture of the container:

/go # uname -m
x86_64

Any idea why protoc can't be executed in this container?


问:
Python: function with list in arguments
I created a function which replace word by special characters in string.
It works well once I need to replace only one word.
Now I need to have possibility to extend list of words from one to more (2, 3 4...).

Working code for one argument - word you can find below.
What I need now is to have possibility to insert more than one word so it could be replaced in code by special signs.

```<code>def cenzura(text, word, sign="#"):
   if word in text:
       return text.replace(word, len(word)*sign)
   else:
       return text

cenzura("The day when I left", "day", sign="$")

</code>```

答:
If you are happy masking all words in the list with the same symbol:

```<code>def cenzura_list(text, word_list, sign="#"):
    for word in word_list:
        text = cenzura(text, word, sign)
    return text

cenzura_list("The day when I left", ["day", "I"], sign="$") # 'The $$$ when $ left'
</code>```

To add: if you do need to mask different words with different symbols, you can use a dict.

```<code>def cenzura_dict(text, mapping_dict):
    for word in mapping_dict.keys():
        text = cenzura(text, word, mapping_dict[word])
    return text

cenzura_dict("The day when I left", {"day":"%", "I":"$"}) # 'The %%% when $ left'
</code>```

Title: Python: function with list in arguments

Body:
I created a function which replace word by special characters in string.
It works well once I need to replace only one word.
Now I need to have possibility to extend list of words from one to more (2, 3 4...).

Working code for one argument - word you can find below.
What I need now is to have possibility to insert more than one word so it could be replaced in code by special signs.

def cenzura(text, word, sign="#"):
   if word in text:
       return text.replace(word, len(word)*sign)
   else:
       return text

cenzura("The day when I left", "day", sign="$")

Body:
If you are happy masking all words in the list with the same symbol:

def cenzura_list(text, word_list, sign="#"):
    for word in word_list:
        text = cenzura(text, word, sign)
    return text

cenzura_list("The day when I left", ["day", "I"], sign="$") # 'The $$$ when $ left'

To add: if you do need to mask different words with different symbols, you can use a dict.

def cenzura_dict(text, mapping_dict):
    for word in mapping_dict.keys():
        text = cenzura(text, word, mapping_dict[word])
    return text

cenzura_dict("The day when I left", {"day":"%", "I":"$"}) # 'The %%% when $ left'


问:
Problems with nullable types in a LINQ Function
Parent_ObjectiveID and identity are int? datatype. In my program should return an object, but it gives an error: Sequence contains no elements.

```<code>int? identity = null;

Objective currentObjective = (from p in cd.Objective
                              where p.Parent_ObjectiveID == identity
                              select p).Single();
</code>```

Although, if I replace identity variable to null. It works, but I don't understand.

```<code>currentObjective = (from p in cd.Objective
                    where p.Parent_ObjectiveID == null
                    select p).Single();
</code>```

What's happening?

UPDATE 1:

I have done this:

```<code>if (identity == null)
{
     currentObjective = (from p in cd.Objective
                         where p.Parent_ObjectiveID == null
                         select p).Single();
}
else
{
     currentObjective = (from p in cd.Objective
                         where p.Parent_ObjectiveID == identity
                         select p).Single();
}
</code>```

But I don't really like it.

答:
```<code>from p in cd.Objective
where p.Parent_ObjectiveID == identity
select p
</code>```

will be compiled to 'select * from objective where Parent_ObjectiveID == @identity'. And,

```<code>from p in cd.Objective
where p.Parent_ObjectiveID == null
select p
</code>```

will be compiled to 'select * from objective where Parent_ObjectiveID is null'.

The clause 'where Parent_ObjectiveID == null' will always return 'false' when your @identity is null.

Body:
Parent_ObjectiveID and identity are int? datatype. In my program should return an object, but it gives an error: Sequence contains no elements.

int? identity = null;

Objective currentObjective = (from p in cd.Objective
                              where p.Parent_ObjectiveID == identity
                              select p).Single();

Although, if I replace identity variable to null. It works, but I don't understand.

currentObjective = (from p in cd.Objective
                    where p.Parent_ObjectiveID == null
                    select p).Single();

What's happening?

UPDATE 1:

I have done this:

if (identity == null)
{
     currentObjective = (from p in cd.Objective
                         where p.Parent_ObjectiveID == null
                         select p).Single();
}
else
{
     currentObjective = (from p in cd.Objective
                         where p.Parent_ObjectiveID == identity
                         select p).Single();
}

But I don't really like it.

Body:
from p in cd.Objective
where p.Parent_ObjectiveID == identity
select p

will be compiled to 'select * from objective where Parent_ObjectiveID == @identity'. And,

from p in cd.Objective
where p.Parent_ObjectiveID == null
select p

will be compiled to 'select * from objective where Parent_ObjectiveID is null'.

The clause 'where Parent_ObjectiveID == null' will always return 'false' when your @identity is null.


问:
Mongodb sort and group by
I'm not sure that my question is correct, but it seems so:

I have a set of rows in my Mongodb, like:

```<code>[{'_id': '5b4c9aa7ddc752c1f5844315',
  'ccode': 'RU',
  'date': '2018-07-16T00:00:00.000Z',
  'rates': {'reg_emails_confirmed': 4,
            'registered': 1,
            'regs_age1': 1,
            'regs_male': 1}},
 {'_id': '5b4cad0dddc752c1f5844322',
  'ccode': 'US',
  'date': '2018-07-16T00:00:00.000Z',
  'rates': {'reg_emails_confirmed': 4,
            'registered': 2,
            'regs_age1': 2,
            'regs_male': 2}},
 {'_id': '5bd88204af4c814883a414b2',
  'ccode': 'US',
  'date': '2018-10-30T00:00:00.000Z',
  'rates': {'reg_emails_confirmed': 2,
            'registered': 1,
            'regs_age1': 1,
            'regs_male': 1}},
 {'_id': '5bd88204af4c814883a414b3',
  'ccode': 'RU',
  'date': '2018-10-30T00:00:00.000Z',
  'rates': {'reg_emails_confirmed': 2,
            'registered': 1,
            'regs_age1': 1,
            'regs_male': 1}}]

</code>```

And I want to sort them by date and combine because for the same date there are multiple rows from different countries.
So the result should look something like ...

```<code>[{'2018-07-16T00:00:00.000Z': [{'_id': '5b4c9aa7ddc752c1f5844315',
                                'ccode': 'RU',
                                'date': '2018-07-16T00:00:00.000Z',
                                'rates': {'reg_emails_confirmed': 4,
                                          'registered': 1,
                                          'regs_age1': 1,
                                          'regs_male': 1}},
                               {'_id': '5b4cad0dddc752c1f5844322',
                                'ccode': 'US',
                                'date': '2018-07-16T00:00:00.000Z',
                                'rates': {'reg_emails_confirmed': 4,
                                          'registered': 2,
                                          'regs_age1': 2,
                                          'regs_male': 2}}]},
 {'2018-10-30T00:00:00.000Z': [{'_id': '5bd88204af4c814883a414b2',
                                'ccode': 'US',
                                'date': '2018-10-30T00:00:00.000Z',
                                'rates': {'reg_emails_confirmed': 2,
                                          'registered': 1,
                                          'regs_age1': 1,
                                          'regs_male': 1}},
                               {'_id': '5bd88204af4c814883a414b3',
                                'ccode': 'RU',
                                'date': '2018-10-30T00:00:00.000Z',
                                'rates': {'reg_emails_confirmed': 2,
                                          'registered': 1,
                                          'regs_age1': 1,
                                          'regs_male': 1}}]}]
</code>```

I tried:

```<code>    db.getCollection('daily_stats').aggregate([
        {'$match': some_condition},
        {'$group': {'ccode': 1}},  # ccode or date?
        {'$sort': {"date": 1}},
    ])
</code>```

But got an error
The field * must be an accumulator object

I googled the error, it's pretty clear, but not seems that related to my case. I don't need any sum, avg, etc functions

答:
Query

sort by date (asceding here, if you need descending put -1)

group by date and collect the ROOT documents

replace the root so you have the date as key

*this assumes you have dates on strings, which is bad idea, if you convert them to date objects, you can still use the query but add
"k":{"$dateToString" : {"date" :"$_id"}}

Test code here

aggregate(
[{"$sort":{"date":1}},
 {"$group":{"_id":"$date", "docs":{"$push":"$$ROOT"}}},
 {"$replaceRoot":
  {"newRoot":{"$arrayToObject":[[{"k":"$_id", "v":"$docs"}]]}}}])
```

Title: Mongodb sort and group by

Body:
I'm not sure that my question is correct, but it seems so:

I have a set of rows in my Mongodb, like:

[{'_id': '5b4c9aa7ddc752c1f5844315',
  'ccode': 'RU',
  'date': '2018-07-16T00:00:00.000Z',
  'rates': {'reg_emails_confirmed': 4,
            'registered': 1,
            'regs_age1': 1,
            'regs_male': 1}},
 {'_id': '5b4cad0dddc752c1f5844322',
  'ccode': 'US',
  'date': '2018-07-16T00:00:00.000Z',
  'rates': {'reg_emails_confirmed': 4,
            'registered': 2,
            'regs_age1': 2,
            'regs_male': 2}},
 {'_id': '5bd88204af4c814883a414b2',
  'ccode': 'US',
  'date': '2018-10-30T00:00:00.000Z',
  'rates': {'reg_emails_confirmed': 2,
            'registered': 1,
            'regs_age1': 1,
            'regs_male': 1}},
 {'_id': '5bd88204af4c814883a414b3',
  'ccode': 'RU',
  'date': '2018-10-30T00:00:00.000Z',
  'rates': {'reg_emails_confirmed': 2,
            'registered': 1,
            'regs_age1': 1,
            'regs_male': 1}}]

And I want to sort them by date and combine because for the same date there are multiple rows from different countries.
So the result should look something like ...

[{'2018-07-16T00:00:00.000Z': [{'_id': '5b4c9aa7ddc752c1f5844315',
                                'ccode': 'RU',
                                'date': '2018-07-16T00:00:00.000Z',
                                'rates': {'reg_emails_confirmed': 4,
                                          'registered': 1,
                                          'regs_age1': 1,
                                          'regs_male': 1}},
                               {'_id': '5b4cad0dddc752c1f5844322',
                                'ccode': 'US',
                                'date': '2018-07-16T00:00:00.000Z',
                                'rates': {'reg_emails_confirmed': 4,
                                          'registered': 2,
                                          'regs_age1': 2,
                                          'regs_male': 2}}]},
 {'2018-10-30T00:00:00.000Z': [{'_id': '5bd88204af4c814883a414b2',
                                'ccode': 'US',
                                'date': '2018-10-30T00:00:00.000Z',
                                'rates': {'reg_emails_confirmed': 2,
                                          'registered': 1,
                                          'regs_age1': 1,
                                          'regs_male': 1}},
                               {'_id': '5bd88204af4c814883a414b3',
                                'ccode': 'RU',
                                'date': '2018-10-30T00:00:00.000Z',
                                'rates': {'reg_emails_confirmed': 2,
                                          'registered': 1,
                                          'regs_age1': 1,
                                          'regs_male': 1}}]}]

I tried:

    db.getCollection('daily_stats').aggregate([
        {'$match': some_condition},
        {'$group': {'ccode': 1}},  # ccode or date?
        {'$sort': {"date": 1}},
    ])

But got an error
The field * must be an accumulator object

I googled the error, it's pretty clear, but not seems that related to my case. I don't need any sum, avg, etc functions


问:
HTML table with fixed headers?
Is there a cross-browser CSS/JavaScript technique to display a long HTML table such that the column headers stay fixed on-screen and do not scroll with the table body. Think of the "freeze panes" effect in Microsoft Excel.

I want to be able to scroll through the contents of the table, but to always be able to see the column headers at the top.

答:
Very late to the party, but as it's still a party, here's my two cents using tailwindcss:

          Timestamp
          Species

          2022-02-09T08:20:39.967Z
          willow

          2022-02-09T08:21:29.453Z
          red osier dogwood

          2022-02-09T08:22:18.984Z
          buttonbush

```

Here's a full working example on tailwind's playgroud.

OwnerDisplayName: Cheekysoft

Title: HTML table with fixed headers?

Body:
Very late to the party, but as it's still a party, here's my two cents using tailwindcss:

<div class="h-screen overflow-hidden flex flex-col">
  <div class="overflow-y-scroll flex-1">
    <table>
      <thead class="sticky top-0">
        <tr>
          <th>Timestamp</th>
          <th>Species</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>2022-02-09T08:20:39.967Z</td>
          <td>willow</td>
        </tr>
        <tr>
          <td>2022-02-09T08:21:29.453Z</td>
          <td>red osier dogwood</td>
        </tr>
        <tr>
          <td>2022-02-09T08:22:18.984Z</td>
          <td>buttonbush</td>
        </tr>
      </tbody>
    </table>
  </div>
</div>

Here's a full working example on tailwind's playgroud.


问:
How do I catch "Index out of range" in Swift?
I would really like to use a more simple classic try catch block in my Swift code but I can't find anything that does it.

I just need:

```<code>try {
// some code that causes a crash.
}
catch {
// okay well that crashed, so lets ignore this block and move on.
}
</code>```

Here's my dilema, when the TableView is reloaded with new data, some information is still siting in RAM which calls didEndDisplayingCell on a tableView with a freshly empty datasource to crash.

So I frequently thrown the exception Index out of range

I've tried this:

```<code>func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {

    do {
        let imageMessageBody = msgSections[indexPath.section].msg[indexPath.row] as? ImageMessageBody
        let cell = tableView.dequeueReusableCellWithIdentifier("ImageUploadCell", forIndexPath: indexPath) as! ImageCell
        cell.willEndDisplayingCell()
    } catch {
        print("Swift try catch is confusing...")
    }
}
</code>```

I've also tried this:

```<code>func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    print(indexPath.section)
    print(indexPath.row)

    if msgSections.count != 0 {
        if let msg = msgSections[indexPath.section].msg[indexPath.row] as? ImageMessageBody {
            let cell = tableView.dequeueReusableCellWithIdentifier("ImageUploadCell", forIndexPath: indexPath) as! ImageCell
            cell.willEndDisplayingCell()
        }
    }
}
</code>```

This is a very low priority block of code, and I have wasted a lot of time with trial and error figuring out which error handler built into swift works for what seems to be extremely unique situations when I have tons of scenarios just like this one where the code can crash and it will not have any effect on the user experience.

In short, I don't need anything fancy but Swift seems to have extremely specific error handlers that differ based on whether I'm getting a value from a functions return value or getting a value from an array's index which may not exist.

Is there a simple try catch on Swift like every other popular programming language?

答:
Don't it's not considered a unusual state error, its a state of its completely screwed up, do something like</p>
```<code>guard array.indicies.contains(index) else { return }
</code>```

Body:
I would really like to use a more simple classic try catch block in my Swift code but I can't find anything that does it.

I just need:

try {
// some code that causes a crash.
}
catch {
// okay well that crashed, so lets ignore this block and move on.
}

Here's my dilema, when the TableView is reloaded with new data, some information is still siting in RAM which calls didEndDisplayingCell on a tableView with a freshly empty datasource to crash.

So I frequently thrown the exception Index out of range

I've tried this:

func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {

    do {
        let imageMessageBody = msgSections[indexPath.section].msg[indexPath.row] as? ImageMessageBody
        let cell = tableView.dequeueReusableCellWithIdentifier("ImageUploadCell", forIndexPath: indexPath) as! ImageCell
        cell.willEndDisplayingCell()
    } catch {
        print("Swift try catch is confusing...")
    }
}

I've also tried this:

func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    print(indexPath.section)
    print(indexPath.row)

    if msgSections.count != 0 {
        if let msg = msgSections[indexPath.section].msg[indexPath.row] as? ImageMessageBody {
            let cell = tableView.dequeueReusableCellWithIdentifier("ImageUploadCell", forIndexPath: indexPath) as! ImageCell
            cell.willEndDisplayingCell()
        }
    }
}

This is a very low priority block of code, and I have wasted a lot of time with trial and error figuring out which error handler built into swift works for what seems to be extremely unique situations when I have tons of scenarios just like this one where the code can crash and it will not have any effect on the user experience.

In short, I don't need anything fancy but Swift seems to have extremely specific error handlers that differ based on whether I'm getting a value from a functions return value or getting a value from an array's index which may not exist.

Is there a simple try catch on Swift like every other popular programming language?

Body:
Don't it's not considered a unusual state error, its a state of its completely screwed up, do something like

guard array.indicies.contains(index) else { return }


问:
What is "Verbose_name" and "Ordering" in class Meta? And please explain a little about Meta Class in django
'''
from django.db import models
import uuid
class Book(models.Model):
name=models.CharField(max_length=100)
isbn=models.UUIDField(default=uuid.uuid4,
primary_key=True)
writer=models.CharField(max_length=100)</p>
```<code>    class Meta:
        ordering=['name']
        ordering='User MetaData'''
</code>```

答:
With class Meta you can give to your model metata such as database table name or ordering options. You can check it out in documentation

By using "verbose_name" in class Meta you can specify human-readable name for singular object. Documentation

By using 'ordering' in class Meta you can specify in which order you will get list of objects. By ['-field_name'] you specify descending order. By ['field_name'] you specify ascending order. You can make ordering by several fields: ordering = ['field1', 'field2']. Documentation

Body:
'''
from django.db import models
import uuid
class Book(models.Model):
name=models.CharField(max_length=100)
isbn=models.UUIDField(default=uuid.uuid4,
primary_key=True)
writer=models.CharField(max_length=100)

    class Meta:
        ordering=['name']
        ordering='User MetaData'''


问:
Sample of lossless image rotate via commons imaging
I found that commons imaging library fits my needs best of all, but there is a lack samples of this library usage.
Does anyone have an example how to rotate jpeg image lossless (i.e. by changing file metadata only)?
Thanks!</p>

答:
See the answer to this question on how to add/remove meta data using the Commons Imaging library.
The tag you would want to set is org.apache.commons.imaging.formats.tiff.constants.TiffTagConstants#TIFF_TAG_ORIENTATION.


Title: reshape from wide to long, simple data.table issue

Body:
I know there must be a one-line data.table solution for this, probably with dcast, but I can't figure it out.

I have data like this:

library(data.table)
data1 <- data.table(
  id = seq(1:5),
  code = c("A","A","B","A","B"),
  date = as.Date( c("2021-08-11","2021-01-05","2021-02-18","2021-02-13","2021-12-13" ))
)
data2 <- data.table(
  id = seq(1:5),
  code = c("B","B","A","B","A"),
  date = as.Date( c("2021-08-13","2021-01-05","2021-02-19","2021-02-14","2021-12-13" ))
)
data3 <- rbind(data1, data2)

I simply wish to reshape to a wide format like this

data_want <- data.table(
  id = seq(1:5),
  code1 = c("A", "A","B","A","B"),
  data1 = c("2021-08-11", "2021-01-05","2021-02-18","2021-02-13","2021-12-13"),
  code2 = c("B", "B","A","B","A"),
  data2 = c("2021-08-13", "2021-01-05","2021-02-19","2021-02-14","2021-12-13")
)

How to do it with dcast?

Body:
You could also make use of rowid as follows

dcast(data3, id ~ rowid(id), value.var = c("code", "date"))
#   id code_1 code_2     date_1     date_2
#1:  1      A      B 2021-08-11 2021-08-13
#2:  2      A      B 2021-01-05 2021-01-05
#3:  3      B      A 2021-02-18 2021-02-19
#4:  4      A      B 2021-02-13 2021-02-14
#5:  5      B      A 2021-12-13 2021-12-13


问:
Combining multiple columns/variables into a single column
I have the following problem (I guess there is an easy answer to it, but I can't figure it out...).

I want to combine multiple columns into a single column. I have 3 variables and there are cases that answered variable 1, cases that answered variable 2, cases that answered variable 3 and cases that answered none of the variables.

Now, I want to combine them all in a single variable, that looks like column vx:

```<code>Ideal result:

  v1 v2 v3 vx
1   1 NA NA  1
2   3 NA NA  3
3   6 NA NA  6
4  NA  5 NA  5
5  NA  1 NA  1
6  NA  3 NA  3
7  NA NA  4  4
8  NA NA  2  2
9  NA NA  1  1
10 NA NA NA NA

</code>```
```<code>v1 <- c(1, 3, 6, NA, NA, NA, NA, NA, NA, NA)
v2 <- c(NA, NA, NA, 5, 1, 3, NA, NA, NA, NA)
v3 <- c(NA, NA, NA, NA, NA, NA, 4, 2, 1, NA)

df <- data.frame(v1, v2, v3)

</code>```

I tried it with df$vx <- paste(df$v1, df$v2, df$v3) but then I get the following result:

```<code>My result:

 v1 v2 v3       vx
1   1 NA NA  1 NA NA
2   3 NA NA  3 NA NA
3   6 NA NA  6 NA NA
4  NA  5 NA  NA 5 NA
5  NA  1 NA  NA 1 NA
6  NA  3 NA  NA 3 NA
7  NA NA  4  NA NA 4
8  NA NA  2  NA NA 2
9  NA NA  1  NA NA 1
10 NA NA NA NA NA NA
</code>```

Can someone tell me how I get a result like the one above (ideal result) without the NAs (except if there are only NAs then I would like to have only one NA in column vx)

I hope I made clear what my issue is.

Thanks a lot!

答:
That is what dplyr::coalesce was made for:

library(dplyr)
df$v4 <- coalesce(!!!df)

#Also works:
df %>%
  mutate(v4 = coalesce(v1, v2, v3))
```
<p>output</p>
<pre class="lang-r prettyprint-override"><code>   v1 v2 v3 v4
1   1 NA NA  1
2   3 NA NA  3
3   6 NA NA  6
4  NA  5 NA  5
5  NA  1 NA  1
6  NA  3 NA  3
7  NA NA  4  4
8  NA NA  2  2
9  NA NA  1  1
10 NA NA NA NA
</code>```

Body:
I have the following problem (I guess there is an easy answer to it, but I can't figure it out...).

I want to combine multiple columns into a single column. I have 3 variables and there are cases that answered variable 1, cases that answered variable 2, cases that answered variable 3 and cases that answered none of the variables.

Now, I want to combine them all in a single variable, that looks like column vx:

Ideal result:

  v1 v2 v3 vx
1   1 NA NA  1
2   3 NA NA  3
3   6 NA NA  6
4  NA  5 NA  5
5  NA  1 NA  1
6  NA  3 NA  3
7  NA NA  4  4
8  NA NA  2  2
9  NA NA  1  1
10 NA NA NA NA

v1 <- c(1, 3, 6, NA, NA, NA, NA, NA, NA, NA)
v2 <- c(NA, NA, NA, 5, 1, 3, NA, NA, NA, NA)
v3 <- c(NA, NA, NA, NA, NA, NA, 4, 2, 1, NA)

df <- data.frame(v1, v2, v3)

I tried it with df$vx <- paste(df$v1, df$v2, df$v3) but then I get the following result:

My result:

 v1 v2 v3       vx
1   1 NA NA  1 NA NA
2   3 NA NA  3 NA NA
3   6 NA NA  6 NA NA
4  NA  5 NA  NA 5 NA
5  NA  1 NA  NA 1 NA
6  NA  3 NA  NA 3 NA
7  NA NA  4  NA NA 4
8  NA NA  2  NA NA 2
9  NA NA  1  NA NA 1
10 NA NA NA NA NA NA

Can someone tell me how I get a result like the one above (ideal result) without the NAs (except if there are only NAs then I would like to have only one NA in column vx)

I hope I made clear what my issue is.

Thanks a lot!

Body:
That is what dplyr::coalesce was made for:

library(dplyr)
df$v4 <- coalesce(!!!df)

#Also works:
df %>%
  mutate(v4 = coalesce(v1, v2, v3))

output

   v1 v2 v3 v4
1   1 NA NA  1
2   3 NA NA  3
3   6 NA NA  6
4  NA  5 NA  5
5  NA  1 NA  1
6  NA  3 NA  3
7  NA NA  4  4
8  NA NA  2  2
9  NA NA  1  1
10 NA NA NA NA


问:
Remove decorator when extending class in Typescript
I have a class which have some decorator I want when extend this class it remove the decorator.

For example:

```<code>class User {
  @IsNotEmpty()
  username: string;

  @IsNotEmpty()
  name: string;
}

class UpdateUser extends User {

}
</code>```

All decorator exist in UpdateUser class which I don't want.
Specifically I'm using class-validator I don't need IsNotEmpty decorator when updating.

Is there any way to remove the decorator when extending class?

Is there any way to replace decorator with other when extending class?

答:
There is no possible way to achieve what you want because these decorators are not only TypeScript things, they also generate JavaScript code which adds side effects at run time (which can be a mutation of the class, and/or some other external effect).

The only thing you could do (very ugly, I strongly advise against it) is to find the actual effects of these decorators to revert them with your own code.

Body:
I have a class which have some decorator I want when extend this class it remove the decorator.

For example:

class User {
  @IsNotEmpty()
  username: string;

  @IsNotEmpty()
  name: string;
}

class UpdateUser extends User {

}

All decorator exist in UpdateUser class which I don't want.
Specifically I'm using class-validator I don't need IsNotEmpty decorator when updating.

Is there any way to remove the decorator when extending class?

Is there any way to replace decorator with other when extending class?