问:
Confused when I should and shouldn't use "const" in C
I have a dictionary that goes like this:

```<code>typedef struct dictNode {
    int key;
    char *value;
    struct dictNode *next;
} Dict;
</code>```

And a get() function that goes like this:

```<code>char *get(const Dict *dict, int key) {
    if(!dict) return NULL;

    Dict *currPtr = dict;

    while(currPtr) {
        if(currPtr->key == key) {
            return currPtr->value;
        }

        currPtr = currPtr->next;
    }
}
</code>```

Compiling this code produces the following error:

dict.c:85: warning: initialization discards qualifiers from pointer target type

This warning refers to the line:

```<code>Dict *currPtr = dict;
</code>```

If I add a "const" before that line like this:

```<code>const Dict *currPtr = dict;
</code>```

The warning goes away...

1) First thing I don't understand is this: I added "const" to the dict argument in get() so that the compiler warns me if I try to change the address dict is pointing to, otherwise I won't be able to access the dictionary in the main program cause I lost the address I was pointing too. Now, I'm creating a new pointer, currPtr, that points to the same place as dict. This way, I use this pointer instead, to traverse the dictionary and keep dict pointer intact. Why do I also need to have const for currPtr?

2) Second thing I don't understand is this: The line currPtr = currPtr->next; is changing the currPtr pointer, so, why doesn't the compile warn me about that if I added a const to currPtr?

Then I have a del() function that goes like this:

```<code>Dict *del(const Dict *dict, int key) {
    if(!dict) return NULL;

    Dict *currPtr = dict;
    Dict *prevPtr = dict;

    while(currPtr) {
        if(currPtr->key == key) {
            prevPtr->next = currPtr->next;
            free(currPtr);
        }

        prevPtr = currPtr;
        currPtr = currPtr->next;
    }

    return dict;
}
</code>```

Please note that I'm aware that this delete function code is not complete, it does not correctly work if I want to delete the first element for instance. It doesn't matter, I'll finish later, it suffices to demonstrate my problem...

3) So, in the get() function I needed to add const to currPtr but in this del() function, I don't need to add const to currPtr nor prevPtr? In both functions I am changing the currPtr pointer and in the case of the del() function I'm changing the prevPtr pointer too. Why does the get() function require me to add a const before currPtr and the del() function does not require me to add a const before currPtr and prevPtr?

I can basically resume this whole post to: When and where exactly in my get() and del() functions should I use const and why, and, when and where I shouldn't?

答:
A const is sort of programmer documentation. It tells yourself that you will not attempt to modify anything that was passed in const qualified.

Your get function should take a const Dict * whereas your del function should not. The currPtr is a walker -- it does not change the logical state of the Dict object in your get so it should be const qualified as well. However, in your del it changes the structure hence -- no const here.

OwnerDisplayName: Nazgulled

ContentLicense: CC BY-SA 2.5

Body:
I have a dictionary that goes like this:

typedef struct dictNode {
    int key;
    char *value;
    struct dictNode *next;
} Dict;

And a get() function that goes like this:

char *get(const Dict *dict, int key) {
    if(!dict) return NULL;

    Dict *currPtr = dict;

    while(currPtr) {
        if(currPtr->key == key) {
            return currPtr->value;
        }

        currPtr = currPtr->next;
    }
}

Compiling this code produces the following error:

dict.c:85: warning: initialization discards qualifiers from pointer target type

This warning refers to the line:

Dict *currPtr = dict;

If I add a "const" before that line like this:

const Dict *currPtr = dict;

The warning goes away...

1) First thing I don't understand is this: I added "const" to the dict argument in get() so that the compiler warns me if I try to change the address dict is pointing to, otherwise I won't be able to access the dictionary in the main program cause I lost the address I was pointing too. Now, I'm creating a new pointer, currPtr, that points to the same place as dict. This way, I use this pointer instead, to traverse the dictionary and keep dict pointer intact. Why do I also need to have const for currPtr?

2) Second thing I don't understand is this: The line currPtr = currPtr->next; is changing the currPtr pointer, so, why doesn't the compile warn me about that if I added a const to currPtr?

Then I have a del() function that goes like this:

Dict *del(const Dict *dict, int key) {
    if(!dict) return NULL;

    Dict *currPtr = dict;
    Dict *prevPtr = dict;

    while(currPtr) {
        if(currPtr->key == key) {
            prevPtr->next = currPtr->next;
            free(currPtr);
        }

        prevPtr = currPtr;
        currPtr = currPtr->next;
    }

    return dict;
}

Please note that I'm aware that this delete function code is not complete, it does not correctly work if I want to delete the first element for instance. It doesn't matter, I'll finish later, it suffices to demonstrate my problem...

3) So, in the get() function I needed to add const to currPtr but in this del() function, I don't need to add const to currPtr nor prevPtr? In both functions I am changing the currPtr pointer and in the case of the del() function I'm changing the prevPtr pointer too. Why does the get() function require me to add a const before currPtr and the del() function does not require me to add a const before currPtr and prevPtr?

I can basically resume this whole post to: When and where exactly in my get() and del() functions should I use const and why, and, when and where I shouldn't?

OwnerDisplayName: dirkgently


来源: stackexchange

问:
Rails - ActionMailer sometimes shows attachments before the email content?
How can I make it so ActionMailer always shows attachments at the bottom of the message:
HTML, TXT, Attachments....

Problem is the attachment here is a text file:

```<code>----==_mimepart_4d8f976d6359a_4f0d15a519e35138763f4
Date: Sun, 27 Mar 2011 13:00:45 -0700
Mime-Version: 1.0
Content-Type: text/plain;
 charset=UTF-8
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
 filename=x00_129999.olk14message
Content-ID: <4d8f976d49c72_4f0d15a519e351387611f@railgun64.53331.mail>
</code>```

Thanks

答:
this is rail 2.3 code (might be slightly different in rails3)

just move you text part before attachment

```<code>recipients  to@domain.com
from      me@domain.com
subject   "some subject"
content_type  "multipart/mixed"

part "text/plain" do |p|
  p.body = render_message 'my_message' #this is template file
end

attachment "application/octet-stream" do |a|
  a.body = File.read("some_file.jpg")
  a.filename = 'name.jpg'
end
</code>```

Body:
How can I make it so ActionMailer always shows attachments at the bottom of the message:
HTML, TXT, Attachments....

Problem is the attachment here is a text file:

----==_mimepart_4d8f976d6359a_4f0d15a519e35138763f4
Date: Sun, 27 Mar 2011 13:00:45 -0700
Mime-Version: 1.0
Content-Type: text/plain;
 charset=UTF-8
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
 filename=x00_129999.olk14message
Content-ID: <4d8f976d49c72_4f0d15a519e351387611f@railgun64.53331.mail>

Thanks

Body:
this is rail 2.3 code (might be slightly different in rails3)

just move you text part before attachment

recipients  to@domain.com
from      me@domain.com
subject   "some subject"
content_type  "multipart/mixed"

part "text/plain" do |p|
  p.body = render_message 'my_message' #this is template file
end

attachment "application/octet-stream" do |a|
  a.body = File.read("some_file.jpg")
  a.filename = 'name.jpg'
end

ContentLicense: CC BY-SA 3.0


问:
How would paginate a json response in my GET request without the use of models/databases?
I'd like to know how I can paginate multiples of 10 with the given response in my GET request when it's not using databases/models.

I've searched around but I'm mostly seeing examples of database/model paginations and not json response paginations.

Below's what I've tried (along with so many other ways but I've ran out of options and hit a wall) but to no avail.

I know there's a way to do this simply but I just can't seem to wrap my head around it.  Any feedback would be appreciated :).

```<code>$response = Http::get(env('endpoint'), $queryParams);

$results = $response->json()['results'];

$numResults = $response->json()['num_results'];

$results->paginate(10); // multiples of ten.  I know this is the Model way of doing it but I can't find any other way to achieve this.
</code>```

答:
You can collect the information:

```<code>collect($results)
</code>```

Then paginate using ->skip(number_to_skip) and then ->take(number_to_take);

Then just return it like you're doing.
It'd be something like:

```<code>$page = $request->page;
$take = 10;
$skip = ($page - 1) * $take;
$resultsCount = collect($results)->count();
$results = collect($results)->skip($skip)->take($take)->all();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'd like to know how I can paginate multiples of 10 with the given response in my GET request when it's not using databases/models.

I've searched around but I'm mostly seeing examples of database/model paginations and not json response paginations.

Below's what I've tried (along with so many other ways but I've ran out of options and hit a wall) but to no avail.

I know there's a way to do this simply but I just can't seem to wrap my head around it.  Any feedback would be appreciated :).

$response = Http::get(env('endpoint'), $queryParams);

$results = $response->json()['results'];

$numResults = $response->json()['num_results'];

$results->paginate(10); // multiples of ten.  I know this is the Model way of doing it but I can't find any other way to achieve this.

Body:
You can collect the information:

collect($results)

Then paginate using ->skip(number_to_skip) and then ->take(number_to_take);

Then just return it like you're doing.
It'd be something like:

$page = $request->page;
$take = 10;
$skip = ($page - 1) * $take;
$resultsCount = collect($results)->count();
$results = collect($results)->skip($skip)->take($take)->all();


问:
Catel.IoC.TypeNotRegisteredException: Catel throws exception even though CanResolve returns true
I have a WPF Application with Catel.Core, Catel.MVVM, Catel.Analyzers and Catel.Fody installed.

When I start the application and try to resolve a Data Access Repository (ILigaMannschaftenZuordnungenRepository) the exception Catel.IoC.TypeNotRegisteredException gets thrown. When I call             dependencyResolver.CanResolve<ILigaMannschaftenZuordnungenRepository>(); it returns true.

I made an extension method to register every service and repository in a single place.

```<code>public static IServiceLocator RegisterDataAccessRepositories(this IServiceLocator services, string dbCon)
{
                services.RegisterInstance(new SpielbetriebDbContext(dbCon));
                services.RegisterType<IDuelleRepository, DuelleRepository>();
                services.RegisterType<IDuellErgebnisseRepository, DuellErgebnisseRepository>();
                services.RegisterType<ILigaMannschaftenZuordnungenRepository, LigaMannschaftenZuordnungenRepository>(); // It is registered!
                services.RegisterType<IMitgliederRepository, MitgliederRepository>();
                services.RegisterType<IPartieDetailsRepository, PartieDetailsRepository>();
                services.RegisterType<IPartienRepository, PartienRepository>();
                services.RegisterType<IProtokollierungenRepository, ProtokollierungenRepository>();
                services.RegisterType<ISaetzeRepository, SaetzeRepository>();
                services
                    .RegisterType<ISpielerPartieErgebnisZuordnungenRepository,
                        SpielerPartieErgebnisZuordnungenRepository>();
                services.RegisterType<ISpielerRepository, SpielerRepository>();
                services.RegisterType<IVereineRepository, VereineRepository>();

                return services;
}
</code>```

When I debug the application and check the registered types of the ServiceLocator it even shows me that ILigaMannschaftenZuordnungenRepository is registered (field _registeredTypes):

The extensions get called in OnStartup. I even tried in the constructor of the App class.

```<code>var serviceLocator = this.GetServiceLocator();
serviceLocator.RegisterDataAccessRepositories(DataConfig.CurrentDbCon); // <--
serviceLocator.RegisterApplicationServices();
</code>```

I tried to call it right away with the Resolve Method

```<code>var dep = this.GetDependencyResolver();
dep.Resolve<ILigaMannschaftenZuordnungenRepository>();
dep.CanResolve<ILigaMannschaftenZuordnungenRepository>(); // returns true
</code>```

What did do I wrong?

Exception Message

答:
Okay, after debugging for quite some time and checking multiple things, I looked into my Data Access Repositories again. And I realized that my repository's implementation had an internal constructor instead of a public constructor. The cause was the base Repository, which had an internal constructor. After changing from internal to public the DI Container resolved the types correctly.

If you are running into this problem, check if your types have public constructors.

Bad:

```<code>internal LigaMannschaftenZuordnungenRepository(SpielbetriebDbContext context) : base(context)
{
}
</code>```

Good:

```<code>public LigaMannschaftenZuordnungenRepository(SpielbetriebDbContext context) : base(context)
{
}
</code>```

Body:
I have a WPF Application with Catel.Core, Catel.MVVM, Catel.Analyzers and Catel.Fody installed.

When I start the application and try to resolve a Data Access Repository (ILigaMannschaftenZuordnungenRepository) the exception Catel.IoC.TypeNotRegisteredException gets thrown. When I call             dependencyResolver.CanResolve<ILigaMannschaftenZuordnungenRepository>(); it returns true.

I made an extension method to register every service and repository in a single place.

public static IServiceLocator RegisterDataAccessRepositories(this IServiceLocator services, string dbCon)
{
                services.RegisterInstance(new SpielbetriebDbContext(dbCon));
                services.RegisterType<IDuelleRepository, DuelleRepository>();
                services.RegisterType<IDuellErgebnisseRepository, DuellErgebnisseRepository>();
                services.RegisterType<ILigaMannschaftenZuordnungenRepository, LigaMannschaftenZuordnungenRepository>(); // It is registered!
                services.RegisterType<IMitgliederRepository, MitgliederRepository>();
                services.RegisterType<IPartieDetailsRepository, PartieDetailsRepository>();
                services.RegisterType<IPartienRepository, PartienRepository>();
                services.RegisterType<IProtokollierungenRepository, ProtokollierungenRepository>();
                services.RegisterType<ISaetzeRepository, SaetzeRepository>();
                services
                    .RegisterType<ISpielerPartieErgebnisZuordnungenRepository,
                        SpielerPartieErgebnisZuordnungenRepository>();
                services.RegisterType<ISpielerRepository, SpielerRepository>();
                services.RegisterType<IVereineRepository, VereineRepository>();

                return services;
}

When I debug the application and check the registered types of the ServiceLocator it even shows me that ILigaMannschaftenZuordnungenRepository is registered (field _registeredTypes):

The extensions get called in OnStartup. I even tried in the constructor of the App class.

var serviceLocator = this.GetServiceLocator();
serviceLocator.RegisterDataAccessRepositories(DataConfig.CurrentDbCon); // <--
serviceLocator.RegisterApplicationServices();

I tried to call it right away with the Resolve Method

var dep = this.GetDependencyResolver();
dep.Resolve<ILigaMannschaftenZuordnungenRepository>();
dep.CanResolve<ILigaMannschaftenZuordnungenRepository>(); // returns true

What did do I wrong?

Exception Message

Body:
Okay, after debugging for quite some time and checking multiple things, I looked into my Data Access Repositories again. And I realized that my repository's implementation had an internal constructor instead of a public constructor. The cause was the base Repository, which had an internal constructor. After changing from internal to public the DI Container resolved the types correctly.

If you are running into this problem, check if your types have public constructors.

Bad:

internal LigaMannschaftenZuordnungenRepository(SpielbetriebDbContext context) : base(context)
{
}

Good:

public LigaMannschaftenZuordnungenRepository(SpielbetriebDbContext context) : base(context)
{
}


问:
Importing a module which have the same name with a system module
My situation is similar to one in this question... The difference is,

In our python/django project, we have a directory called utils, which keeps basic functions...

Sometimes, we need to test some modules by running thm from console like

```<code>python myproject/some_module.py
</code>```

It is all good, until python tries to import something from our utils directory...

```<code>from utils.custom_modules import some_function
ImportError: No module named custom_modules
</code>```

I check my python path, and our project is on the list, each folder under the project file has __init__.py files, and when i run ipython within project directory... Everything is ok, otherwise, python imports from its own utils directory...

My collegues use the sama method without any problem, but it throws ImportError on my environment... What could be the problem that all of us was missing?

UPDATE: My project directory, and each sub-drectory have __init__.py file, and i can import other modules from my project without any problem... When i am in a diffrent folder than my procekt and i run ipython, a such import have no problem...

```<code>from someothermodule.submodule imprort blahblahblah
</code>```

But, when it comes to importing utils, it fails...

UPATE 2: What caused the problem was the utils directory under django folder, which is also in the python path...

答:
See the PEP on absolute and relative imports for the semantics. You probably want

```<code>from .utils.custom_modules import some_function
</code>```

if you're in a file at the top level of your package.

Edit: This can only be done from inside a package. This is for a good reason -- if you're importing something that is part of your project, then you're already treating it like a Python package, and you should actually make it one. You do this by adding an __init__.py file to project directory.

Edit 2: You've completely changed the question. It may be possible to work around the problem, but the correct thing to do is not refer to your packed the same way as a builtin package. You either need to rename utils, or make it a subpackage of another package, so you can refer to it by a non-conflicting name (like from mydjangoapp.utils.custom_modules import some_function).

Body:
My situation is similar to one in this question... The difference is,

In our python/django project, we have a directory called utils, which keeps basic functions...

Sometimes, we need to test some modules by running thm from console like

python myproject/some_module.py

It is all good, until python tries to import something from our utils directory...

from utils.custom_modules import some_function
ImportError: No module named custom_modules

I check my python path, and our project is on the list, each folder under the project file has __init__.py files, and when i run ipython within project directory... Everything is ok, otherwise, python imports from its own utils directory...

My collegues use the sama method without any problem, but it throws ImportError on my environment... What could be the problem that all of us was missing?

UPDATE: My project directory, and each sub-drectory have __init__.py file, and i can import other modules from my project without any problem... When i am in a diffrent folder than my procekt and i run ipython, a such import have no problem...

from someothermodule.submodule imprort blahblahblah

But, when it comes to importing utils, it fails...

UPATE 2: What caused the problem was the utils directory under django folder, which is also in the python path...

Body:
See the PEP on absolute and relative imports for the semantics. You probably want

from .utils.custom_modules import some_function

if you're in a file at the top level of your package.

Edit: This can only be done from inside a package. This is for a good reason -- if you're importing something that is part of your project, then you're already treating it like a Python package, and you should actually make it one. You do this by adding an __init__.py file to project directory.

Edit 2: You've completely changed the question. It may be possible to work around the problem, but the correct thing to do is not refer to your packed the same way as a builtin package. You either need to rename utils, or make it a subpackage of another package, so you can refer to it by a non-conflicting name (like from mydjangoapp.utils.custom_modules import some_function).


问:
How do I create a notification that will be triggered every 8 in 8 hours, 12 in 12, programmatically in Swift iOS
I'm creating an app to notify the user to take his Medicine.

I'm already storing your selection of periods, like, 2 in 2 hours, 8 in 8, etc.
I'm converting to a double and then multiplying by 3600 in the addingTimeInterval method, as shown below.

func notifications(name: String, timeToTime: String, firstTime: String) {
    let center = UNUserNotificationCenter.current()

    let content = UNMutableNotificationContent()
    content.title = "Chegou a hora de tomar \(name)"
    content.body = "Voce deve ingerir este remédio \(timeToTime)"
    content.sound = UNNotificationSound.default

    let timeInterval = handleToInt(time: timeToTime)
    let date = Date().addingTimeInterval(timeInterval * 3600)
    let dateComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)
    let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)

    let request = UNNotificationRequest(identifier: "random", content: content, trigger: trigger)

    center.add(request)
}
```
<p>That way, I set the first alarm for X hours from now, for example, selecting 2 in 2 hours, I convert it to 2, and the user will be notified in 2 hours</p>
<p>The timeToTime variable is his choice of interval. The method handleToInt converts to an int or a double.</p>
<p>I'm very lost here...</p>
<p>Here are the other methods that appear in the code</p>
<pre class="lang-swift prettyprint-override"><code>private func handleTime(timeToTime: String) -> String {
    var timeToTime = timeToTime
    switch timeToTime {
    case "2 em 2 horas":
        timeToTime = "2"
    case "4 em 4 horas":
        timeToTime = "4"
    case "6 em 6 horas":
        timeToTime = "6"
    case "8 em 8 horas":
        timeToTime = "8"
    case "12 em 12 horas":
        timeToTime = "4"
    default:
        timeToTime = "8"
    }
    return timeToTime
}

func handleToInt(time: String) -> Double {
    let timeToInt = handleTime(timeToTime: time)
    let myInt = (timeToInt as NSString).integerValue

    return Double(myInt)
}
</code>```

答:
You can use UNTimeIntervalNotificationTrigger, e.g.:

// Fire every 2 hours (60 seconds × 60 minutes × 2 hours)
let hours = 2
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: TimeInterval(hours) * 60 * 60, repeats: true)
```

Body:
I'm creating an app to notify the user to take his Medicine.

I'm already storing your selection of periods, like, 2 in 2 hours, 8 in 8, etc.
I'm converting to a double and then multiplying by 3600 in the addingTimeInterval method, as shown below.

func notifications(name: String, timeToTime: String, firstTime: String) {
    let center = UNUserNotificationCenter.current()

    let content = UNMutableNotificationContent()
    content.title = "Chegou a hora de tomar \(name)"
    content.body = "Voce deve ingerir este remédio \(timeToTime)"
    content.sound = UNNotificationSound.default

    let timeInterval = handleToInt(time: timeToTime)
    let date = Date().addingTimeInterval(timeInterval * 3600)
    let dateComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)
    let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)

    let request = UNNotificationRequest(identifier: "random", content: content, trigger: trigger)

    center.add(request)
}

That way, I set the first alarm for X hours from now, for example, selecting 2 in 2 hours, I convert it to 2, and the user will be notified in 2 hours

The timeToTime variable is his choice of interval. The method handleToInt converts to an int or a double.

I'm very lost here...

Here are the other methods that appear in the code

private func handleTime(timeToTime: String) -> String {
    var timeToTime = timeToTime
    switch timeToTime {
    case "2 em 2 horas":
        timeToTime = "2"
    case "4 em 4 horas":
        timeToTime = "4"
    case "6 em 6 horas":
        timeToTime = "6"
    case "8 em 8 horas":
        timeToTime = "8"
    case "12 em 12 horas":
        timeToTime = "4"
    default:
        timeToTime = "8"
    }
    return timeToTime
}

func handleToInt(time: String) -> Double {
    let timeToInt = handleTime(timeToTime: time)
    let myInt = (timeToInt as NSString).integerValue

    return Double(myInt)
}


问:
rabbitmq log file scraping: are all the logging levels abbreviated to 4 characters?

I plan on scraping all the Rabbitmq log files via fluentd and so I wanted a rule to make sure all the error messages were captured.

I noticed immediately that all my log file messages have abbreviations for the logging levels.

so for example [info] and [warn] messages

rabbitmq log file scraping: are all the logging levels abbreviated to 4 characters? if yes, what is the abbreviation for the error level?

What is the abbreviation for all the others logging level names with longer than 4 characters?

Thanks in advance.

答:
Log levels are found here:  https://www.rabbitmq.com/logging.html#log-levels

There are also dbug, noti, erro, and crit


问:
How to aggregate the sum of all keys in an object in mongodb
Each document has a field contributions which is an object with a name and a a positive integer:

```<code>{contributions: { "jerry": 11, "jenny": 83, "jimmy": 3}}
{contributions: { "jerry": 25, "jimmy": 53}}
{contributions: { "jenny": 83, "jimmy": 3, "carlos": 9}}
</code>```

I want to aggregate this (using mongo-node) such that the output reduce to the total sum per user. The format does not matter much, this would be ok:

```<code>{contributions: { "jerry": 119, "jenny": 166, "jimmy": 59, "carlos": 9}}
</code>```

Or alternatively this format would also be fine:

```<code>{"user": "jerry", "total": 119}
{"user": "jenny", "total": 166}
{"user": "jimmy", "total": 59}
{"user": "carlos", "total": 9}
</code>```

Can I do this with an aggregate, or map-reduce? The issue where I get stuck is that all examples seem to assume a fixed keys, but in my case the keys are dynamic.

答:
Storing data in the field name is usually considered and anti-pattern with MongoDB.

Instead of

```<code>{contributions: { "jerry": 11, "jenny": 83, "jimmy": 3}}
</code>```

Store it as

```<code>{contributions: [
   { name: "jerry", amount:11 },
   { name:"jenny", amount: 83 },
   { name:"jimmy", amount: 3 }
]}
</code>```

This would allow index support for contributor names/amounts, and slightly simpler aggregation:

```<code>[
  {$unwind: "$contributions"},
  {$group: { _id:"$contributions.name", total: {$sum: "$contributions.amount"}}
]
</code>```

If you really must keep using fieldname as data, you will likely need to convert that object to an array first, like:

```<code>[
  {$addFields: {contributions: {$objectToArray:"$contributions}}},
  {$unwind: "$contributions"},
  {$group: {_id: "$contributions.k", total: {$sum: "$contributions.v}}
]
</code>```

Body:
Each document has a field contributions which is an object with a name and a a positive integer:

{contributions: { "jerry": 11, "jenny": 83, "jimmy": 3}}
{contributions: { "jerry": 25, "jimmy": 53}}
{contributions: { "jenny": 83, "jimmy": 3, "carlos": 9}}

I want to aggregate this (using mongo-node) such that the output reduce to the total sum per user. The format does not matter much, this would be ok:

{contributions: { "jerry": 119, "jenny": 166, "jimmy": 59, "carlos": 9}}

Or alternatively this format would also be fine:

{"user": "jerry", "total": 119}
{"user": "jenny", "total": 166}
{"user": "jimmy", "total": 59}
{"user": "carlos", "total": 9}

Can I do this with an aggregate, or map-reduce? The issue where I get stuck is that all examples seem to assume a fixed keys, but in my case the keys are dynamic.

Body:
Storing data in the field name is usually considered and anti-pattern with MongoDB.

Instead of

{contributions: { "jerry": 11, "jenny": 83, "jimmy": 3}}

Store it as

{contributions: [
   { name: "jerry", amount:11 },
   { name:"jenny", amount: 83 },
   { name:"jimmy", amount: 3 }
]}

This would allow index support for contributor names/amounts, and slightly simpler aggregation:

[
  {$unwind: "$contributions"},
  {$group: { _id:"$contributions.name", total: {$sum: "$contributions.amount"}}
]

If you really must keep using fieldname as data, you will likely need to convert that object to an array first, like:

[
  {$addFields: {contributions: {$objectToArray:"$contributions}}},
  {$unwind: "$contributions"},
  {$group: {_id: "$contributions.k", total: {$sum: "$contributions.v}}
]


问:
access java object in javascript
I am using spring framework. I am passing java bean object as model attribute to JSP. On JSP I am calling a javascript function passing this java bean object. I need to access memebers of this object inside the javascript. below is the code snippet

```<code>Test.jsp
..
..
<form:radiobutton id="showdialog" path="nextAction" value="showdialog" label="show dialog"
    onclick="javascript: showDiseaseGroupDialog('${dataRequestFormDTO}');"/></span></div>
..
..

Common.js
function showDiseaseGroupDialog(dataRequestFormDTO){

    alert("DG:"+dataRequestFormDTO.selectedDiseaseGroup);
    for(var diseaseGroupDTO in dataRequestFormDTO.availableDiseaseGroups.values){
        alert(diseaseGroupDTO.name);
    }
}

DataRequestFormDTO.java
public class DataRequestFormDTO{
    private String selectedDiseaseGroup;
    private Map<String, DiseaseGroupDTO> availableDiseaseGroups;

    public String getSelectedDiseaseGroup() {
        return selectedDiseaseGroups;
    }

    public void setSelectedDiseaseGroup(String selectedDiseaseGroup) {
        this.selectedDiseaseGroup = selectedDiseaseGroup;
    }

    public Map<String, DiseaseGroupDTO> getAvailableDiseaseGroups() {
        return availableDiseaseGroups;
    }

    public void setAvailableDiseaseGroups(
            Map<String, DiseaseGroupDTO> availableDiseaseGroups) {
        this.availableDiseaseGroups = availableDiseaseGroups;
    }
}

public class DiseaseGroupDTO {

    private String id;
    private String name;

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

}
</code>```

Problem is I am getting error in showDiseaseGroupDialog function. First alert displays "DG:undefined" and javascript error "availableDiseaseGroups is undefined".

I want to understand

Why java bean members are not accessible in javascript? Though in jsp I can print the same values.

how hashmap/arraylist can access in javascript?

答: Javascript is poorly named, it has nothing to do with Java.  You can't use a java object directly in javascript just like you can't use a C++ object in it.</p>

Title: access java object in javascript

Body:
I am using spring framework. I am passing java bean object as model attribute to JSP. On JSP I am calling a javascript function passing this java bean object. I need to access memebers of this object inside the javascript. below is the code snippet

Test.jsp
..
..
<form:radiobutton id="showdialog" path="nextAction" value="showdialog" label="show dialog"
    onclick="javascript: showDiseaseGroupDialog('${dataRequestFormDTO}');"/>

..
..

Common.js
function showDiseaseGroupDialog(dataRequestFormDTO){

    alert("DG:"+dataRequestFormDTO.selectedDiseaseGroup);
    for(var diseaseGroupDTO in dataRequestFormDTO.availableDiseaseGroups.values){
        alert(diseaseGroupDTO.name);
    }
}

DataRequestFormDTO.java
public class DataRequestFormDTO{
    private String selectedDiseaseGroup;
    private Map<String, DiseaseGroupDTO> availableDiseaseGroups;

    public String getSelectedDiseaseGroup() {
        return selectedDiseaseGroups;
    }

    public void setSelectedDiseaseGroup(String selectedDiseaseGroup) {
        this.selectedDiseaseGroup = selectedDiseaseGroup;
    }

    public Map<String, DiseaseGroupDTO> getAvailableDiseaseGroups() {
        return availableDiseaseGroups;
    }

    public void setAvailableDiseaseGroups(
            Map<String, DiseaseGroupDTO> availableDiseaseGroups) {
        this.availableDiseaseGroups = availableDiseaseGroups;
    }
}

public class DiseaseGroupDTO {

    private String id;
    private String name;

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

}

Problem is I am getting error in showDiseaseGroupDialog function. First alert displays "DG:undefined" and javascript error "availableDiseaseGroups is undefined".

I want to understand

Why java bean members are not accessible in javascript? Though in jsp I can print the same values.

how hashmap/arraylist can access in javascript?


问:
How to limit the mui grid to a box
I made a multi-card grid layout with Mui grid

I want to limit the grid box to a particular region on screen, something like:

the user should have to scroll to see the rest

This is the code that doesn't work as I want it to

```<code>    return (
        <Box className={classes.pageContainer}>
            <Typography className={classes.backgroundText}>WORKS</Typography>
            <Box sx={{ height: '600px' }}>
                <Grid container spacing={6} className={classes.gridContainer} justifyContent="center">
                    {temporaryVideos.map((cardInfo, ndx) => {
                        return (
                            <Grid item>
                                <VideoCard cardInfo={cardInfo} index={ndx} />
                            </Grid>
                        );
                    })}
                </Grid>
            </Box>
        </Box>
    );
</code>```

Thanks in advance

Rafael

答:
I did it

I placed an "overflowY: 'auto'" on the grid container

Title: How to limit the mui grid to a box

Body:
I made a multi-card grid layout with Mui grid

I want to limit the grid box to a particular region on screen, something like:

the user should have to scroll to see the rest

This is the code that doesn't work as I want it to

    return (
        <Box className={classes.pageContainer}>
            <Typography className={classes.backgroundText}>WORKS</Typography>
            <Box sx={{ height: '600px' }}>
                <Grid container spacing={6} className={classes.gridContainer} justifyContent="center">
                    {temporaryVideos.map((cardInfo, ndx) => {
                        return (
                            <Grid item>
                                <VideoCard cardInfo={cardInfo} index={ndx} />
                            </Grid>
                        );
                    })}
                </Grid>
            </Box>
        </Box>
    );

Thanks in advance

Rafael


问:
"No numeric types to aggregate" while using Pandas expanding()
In Pandas 1.1.4, I am receiving a DataError: No numeric types to aggregate when using an ExpandingGroupby.

Example dataset:

```<code>tmp = pd.DataFrame({'col1':['a','b','b','c','d','d'], 'col2': ['red','red','green','green','red','blue']})

print(tmp)

col1    col2
a       red
b       red
b       green
c       green
d       red
d       blue
</code>```

This works:

```<code>tmp.groupby('col1').agg(lambda x: ','.join(x))
</code>```

And this works:

```<code>tmp.groupby('col1').expanding().agg('count')
</code>```

But this returns an error:

```<code>tmp.groupby('col1').expanding().agg(lambda x: ','.join(x))
</code>```

DataError: No numeric types to aggregate

There is no conceptual reason this shouldn't work, and there are several references online to people using custom functions within an ExpandingGroupby.

There is obviously no reason that this should need to be a numeric, especially given that the count works with the non-numeric column.  What is happening here?  If this can't be done natively for whatever reason, how can I do it manually?

答:
If you want to join the previous rows values to the next inside the group, perhaps you could use cumsum and add strings as you go:

```<code>tmp['expading_join'] = tmp.groupby('col1')['col2'].apply(lambda x: (x + ',').cumsum()).str.rstrip(',')
</code>```

Output:

```<code>  col1   col2 expading_join
0    a    red           red
1    b    red           red
2    b  green     red,green
3    c  green         green
4    d    red           red
5    d   blue      red,blue
</code>```

Body:
In Pandas 1.1.4, I am receiving a DataError: No numeric types to aggregate when using an ExpandingGroupby.

Example dataset:

tmp = pd.DataFrame({'col1':['a','b','b','c','d','d'], 'col2': ['red','red','green','green','red','blue']})

print(tmp)

col1    col2
a       red
b       red
b       green
c       green
d       red
d       blue

This works:

tmp.groupby('col1').agg(lambda x: ','.join(x))

And this works:

tmp.groupby('col1').expanding().agg('count')

But this returns an error:

tmp.groupby('col1').expanding().agg(lambda x: ','.join(x))

DataError: No numeric types to aggregate

There is no conceptual reason this shouldn't work, and there are several references online to people using custom functions within an ExpandingGroupby.

There is obviously no reason that this should need to be a numeric, especially given that the count works with the non-numeric column.  What is happening here?  If this can't be done natively for whatever reason, how can I do it manually?

Body:
If you want to join the previous rows values to the next inside the group, perhaps you could use cumsum and add strings as you go:

tmp['expading_join'] = tmp.groupby('col1')['col2'].apply(lambda x: (x + ',').cumsum()).str.rstrip(',')

Output:

  col1   col2 expading_join
0    a    red           red
1    b    red           red
2    b  green     red,green
3    c  green         green
4    d    red           red
5    d   blue      red,blue


问:
How i can reapirt problem in new flutter project
When i create new flutter project and click run i have this problem

"Could not initialize class com.android.sdklib.repository.AndroidSdkHandler"

enter image description here

Flutter doctor
enter image description here

答: Run this in the console: flutter clean

Body: Run this in the console: flutter clean


问:
Getting an existing React App up and running
I'm trying to get an already existing React App running locally on my Mac. I have all the source files, and have node.js installed on my machine.

When I run npm install I'm greeted with a long list of deprecations and npm ERRors. A list so long it far exceeds the Stack overflow character limit. Here's how it ends.

```<code>npm ERR! 2 warnings generated.
npm ERR! In file included from ../src/libsass/src/util.cpp:3:
npm ERR! ../src/libsass/src/ast.hpp:1614:25: warning: loop variable 'numerator' creates a copy from type 'const std::__1::basic_string<char>' [-Wrange-loop-construct]
npm ERR!         for (const auto numerator : numerators)
npm ERR!                         ^
npm ERR! ../src/libsass/src/ast.hpp:1614:14: note: use reference type 'const std::__1::basic_string<char> &' to prevent copying
npm ERR!         for (const auto numerator : numerators)
npm ERR!              ^~~~~~~~~~~~~~~~~~~~~~
npm ERR!                         &
npm ERR! ../src/libsass/src/ast.hpp:1616:25: warning: loop variable 'denominator' creates a copy from type 'const std::__1::basic_string<char>' [-Wrange-loop-construct]
npm ERR!         for (const auto denominator : denominators)
npm ERR!                         ^
npm ERR! ../src/libsass/src/ast.hpp:1616:14: note: use reference type 'const std::__1::basic_string<char> &' to prevent copying
npm ERR!         for (const auto denominator : denominators)
npm ERR!              ^~~~~~~~~~~~~~~~~~~~~~~~
npm ERR!                         &
npm ERR! 2 warnings generated.
npm ERR! In file included from ../src/libsass/src/values.cpp:3:
npm ERR! In file included from ../src/libsass/src/values.hpp:4:
npm ERR! ../src/libsass/src/ast.hpp:1614:25: warning: loop variable 'numerator' creates a copy from type 'const std::__1::basic_string<char>' [-Wrange-loop-construct]
npm ERR!         for (const auto numerator : numerators)
npm ERR!                         ^
npm ERR! ../src/libsass/src/ast.hpp:1614:14: note: use reference type 'const std::__1::basic_string<char> &' to prevent copying
npm ERR!         for (const auto numerator : numerators)
npm ERR!              ^~~~~~~~~~~~~~~~~~~~~~
npm ERR!                         &
npm ERR! ../src/libsass/src/ast.hpp:1616:25: warning: loop variable 'denominator' creates a copy from type 'const std::__1::basic_string<char>' [-Wrange-loop-construct]
npm ERR!         for (const auto denominator : denominators)
npm ERR!                         ^
npm ERR! ../src/libsass/src/ast.hpp:1616:14: note: use reference type 'const std::__1::basic_string<char> &' to prevent copying
npm ERR!         for (const auto denominator : denominators)
npm ERR!              ^~~~~~~~~~~~~~~~~~~~~~~~
npm ERR!                         &
npm ERR! 2 warnings generated.
npm ERR! In file included from ../src/binding.cpp:1:
npm ERR! In file included from ../../nan/nan.h:58:
npm ERR! In file included from /Users/USER/.node-gyp/16.13.1/include/node/node.h:63:
npm ERR! In file included from /Users/USER/.node-gyp/16.13.1/include/node/v8.h:30:
npm ERR! /Users/USER/.node-gyp/16.13.1/include/node/v8-internal.h:492:38: error: no template named 'remove_cv_t' in namespace 'std'; did you mean 'remove_cv'?
npm ERR!             !std::is_same<Data, std::remove_cv_t<T>>::value>::Perform(data);
npm ERR!                                 ~~~~~^~~~~~~~~~~
npm ERR!                                      remove_cv
npm ERR! /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/type_traits:776:50: note: 'remove_cv' declared here
npm ERR! template <class _Tp> struct _LIBCPP_TEMPLATE_VIS remove_cv
npm ERR!                                                  ^
npm ERR! 1 error generated.
npm ERR! make: *** [Release/obj.target/binding/src/binding.o] Error 1
npm ERR! gyp ERR! build error
npm ERR! gyp ERR! stack Error: `make` failed with exit code: 2
npm ERR! gyp ERR! stack     at ChildProcess.onExit (/Users/USER/Desktop/it-cc/node_modules/node-gyp/lib/build.js:262:23)
npm ERR! gyp ERR! stack     at ChildProcess.emit (node:events:390:28)
npm ERR! gyp ERR! stack     at Process.ChildProcess._handle.onexit (node:internal/child_process:290:12)
npm ERR! gyp ERR! System Darwin 20.6.0
npm ERR! gyp ERR! command "/usr/local/bin/node" "/Users/USER/Desktop/it-cc/node_modules/node-gyp/bin/node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="
npm ERR! gyp ERR! cwd /Users/USER/Desktop/it-cc/node_modules/node-sass
npm ERR! gyp ERR! node -v v16.13.1
npm ERR! gyp ERR! node-gyp -v v3.8.0
npm ERR! gyp ERR! not ok
npm ERR! Build failed with error code: 1

</code>```

I have tried the following:

Making sure all lock files & node_module directory is deleted

Cleared cache by npm cache clear --force

npm audit fix

I'm a bit of a noob to React and would really appreciate any help!

package.json contents:

```<code>{
  "name": "marketing-roi",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@material-ui/core": "^4.10.0",
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "node-sass": "^4.14.1",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-redux": "^7.2.0",
    "react-scripts": "3.4.1",
    "redux": "^4.0.5",
    "redux-thunk": "^2.3.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}
</code>```

答:
The answer was to replace node-sass with sass in my package.json file, and editing the version to a valid one (in my case I chose the latest build 1.47.0).

I'm running a current version of node on my machine and was specifying an old version node-sass that was no longer supported in my package.json file since the app was built a couple years ago. Deprecation Announcement

Thanks to @Jared Smith

Body:
I'm trying to get an already existing React App running locally on my Mac. I have all the source files, and have node.js installed on my machine.

When I run npm install I'm greeted with a long list of deprecations and npm ERRors. A list so long it far exceeds the Stack overflow character limit. Here's how it ends.

npm ERR! 2 warnings generated.
npm ERR! In file included from ../src/libsass/src/util.cpp:3:
npm ERR! ../src/libsass/src/ast.hpp:1614:25: warning: loop variable 'numerator' creates a copy from type 'const std::__1::basic_string<char>' [-Wrange-loop-construct]
npm ERR!         for (const auto numerator : numerators)
npm ERR!                         ^
npm ERR! ../src/libsass/src/ast.hpp:1614:14: note: use reference type 'const std::__1::basic_string<char> &' to prevent copying
npm ERR!         for (const auto numerator : numerators)
npm ERR!              ^~~~~~~~~~~~~~~~~~~~~~
npm ERR!                         &
npm ERR! ../src/libsass/src/ast.hpp:1616:25: warning: loop variable 'denominator' creates a copy from type 'const std::__1::basic_string<char>' [-Wrange-loop-construct]
npm ERR!         for (const auto denominator : denominators)
npm ERR!                         ^
npm ERR! ../src/libsass/src/ast.hpp:1616:14: note: use reference type 'const std::__1::basic_string<char> &' to prevent copying
npm ERR!         for (const auto denominator : denominators)
npm ERR!              ^~~~~~~~~~~~~~~~~~~~~~~~
npm ERR!                         &
npm ERR! 2 warnings generated.
npm ERR! In file included from ../src/libsass/src/values.cpp:3:
npm ERR! In file included from ../src/libsass/src/values.hpp:4:
npm ERR! ../src/libsass/src/ast.hpp:1614:25: warning: loop variable 'numerator' creates a copy from type 'const std::__1::basic_string<char>' [-Wrange-loop-construct]
npm ERR!         for (const auto numerator : numerators)
npm ERR!                         ^
npm ERR! ../src/libsass/src/ast.hpp:1614:14: note: use reference type 'const std::__1::basic_string<char> &' to prevent copying
npm ERR!         for (const auto numerator : numerators)
npm ERR!              ^~~~~~~~~~~~~~~~~~~~~~
npm ERR!                         &
npm ERR! ../src/libsass/src/ast.hpp:1616:25: warning: loop variable 'denominator' creates a copy from type 'const std::__1::basic_string<char>' [-Wrange-loop-construct]
npm ERR!         for (const auto denominator : denominators)
npm ERR!                         ^
npm ERR! ../src/libsass/src/ast.hpp:1616:14: note: use reference type 'const std::__1::basic_string<char> &' to prevent copying
npm ERR!         for (const auto denominator : denominators)
npm ERR!              ^~~~~~~~~~~~~~~~~~~~~~~~
npm ERR!                         &
npm ERR! 2 warnings generated.
npm ERR! In file included from ../src/binding.cpp:1:
npm ERR! In file included from ../../nan/nan.h:58:
npm ERR! In file included from /Users/USER/.node-gyp/16.13.1/include/node/node.h:63:
npm ERR! In file included from /Users/USER/.node-gyp/16.13.1/include/node/v8.h:30:
npm ERR! /Users/USER/.node-gyp/16.13.1/include/node/v8-internal.h:492:38: error: no template named 'remove_cv_t' in namespace 'std'; did you mean 'remove_cv'?
npm ERR!             !std::is_same<Data, std::remove_cv_t<T>>::value>::Perform(data);
npm ERR!                                 ~~~~~^~~~~~~~~~~
npm ERR!                                      remove_cv
npm ERR! /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/type_traits:776:50: note: 'remove_cv' declared here
npm ERR! template <class _Tp> struct _LIBCPP_TEMPLATE_VIS remove_cv
npm ERR!                                                  ^
npm ERR! 1 error generated.
npm ERR! make: *** [Release/obj.target/binding/src/binding.o] Error 1
npm ERR! gyp ERR! build error
npm ERR! gyp ERR! stack Error: `make` failed with exit code: 2
npm ERR! gyp ERR! stack     at ChildProcess.onExit (/Users/USER/Desktop/it-cc/node_modules/node-gyp/lib/build.js:262:23)
npm ERR! gyp ERR! stack     at ChildProcess.emit (node:events:390:28)
npm ERR! gyp ERR! stack     at Process.ChildProcess._handle.onexit (node:internal/child_process:290:12)
npm ERR! gyp ERR! System Darwin 20.6.0
npm ERR! gyp ERR! command "/usr/local/bin/node" "/Users/USER/Desktop/it-cc/node_modules/node-gyp/bin/node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="
npm ERR! gyp ERR! cwd /Users/USER/Desktop/it-cc/node_modules/node-sass
npm ERR! gyp ERR! node -v v16.13.1
npm ERR! gyp ERR! node-gyp -v v3.8.0
npm ERR! gyp ERR! not ok
npm ERR! Build failed with error code: 1

I have tried the following:

Making sure all lock files & node_module directory is deleted

Cleared cache by npm cache clear --force

npm audit fix

I'm a bit of a noob to React and would really appreciate any help!

package.json contents:

{
  "name": "marketing-roi",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@material-ui/core": "^4.10.0",
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "node-sass": "^4.14.1",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-redux": "^7.2.0",
    "react-scripts": "3.4.1",
    "redux": "^4.0.5",
    "redux-thunk": "^2.3.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}


问:
How do transitive dependencies work in Python pip?
I have an automated machine build that installs a Python package (Package A) with a ton of dependencies (Packages X, Y, and Z).  Package A doesn't pin the versions of packages X, Y, or Z, so even though I pin the version for package A, there have been a bunch of times when my builds fail because of a breaking update in package X.

To fix this, I was planning on making a requirements.txt file that pinned explicit versions of A, X, Y, and Z (rather than just A, which is what happens now).  This should work assuming pip has proper support for both pinning and transitive dependency resolution.

It seems like this works with my current version of pip, but I've found a lot of conflicting information about how pip handles these things (eg, this thread with 100 comments talking about how pip dependency resolution isn't great).

So my questions:

How does dependency resolution work in pip?  If package A depends on X>=7, and my top-level requirements.txt specifies X==8, is it possible that pip would install X version 9 because it looks at A first and tries to get the most recent version of transitive dependencies?

Is there a canonical / authoritative source describing how dependency resolution works in pip?  The best I've been able to find is this page, but some of the comments I've seen online make it seem like that page isn't 100% correct where transitive dependencies are concerned.

Thanks!

答:
pip introduced a new resolver in 20.3 and from 21.0 this is now the default resolver.

The new resolver fixes the inconsistencies outlined in your first question and not only that. When dependency packages are inconsistent (e.g. X>=7 and X==6) it will reject the installation all together.

The new resolver is resolvelib based so you can find details about the algorithm there but pip also updated the docs about dependency resolution with some details like the backtracking they do.


问:
How to get previous day's records in MongodDB?
I am using MongoDB which has a time field in milliseconds. I am trying to get all the records for previous day.
So far I have searched for solutions which show how to get the records for previous 24 hrs. But I need records for previous day only. Please help to write this query.
So something like this

```<code>createdTime: {
     $lt: new Date().getTime(),
     $gt: new Date().getTime() - 1000 * 60 * 60 * 24,
},
</code>```

But like I explained this is not what I want.

答:
Whenever you have to work with date/time arithmetic then I recommend moment.js library:

```<code>createdTime: {
   $lt: moment().endOf('day').subtract(1, 'day').toDate(),
   $gte: moment().startOf('day').subtract(1, 'day').toDate()
},
</code>```

Alternative libraries are luxon and day.js

Body:
I am using MongoDB which has a time field in milliseconds. I am trying to get all the records for previous day.
So far I have searched for solutions which show how to get the records for previous 24 hrs. But I need records for previous day only. Please help to write this query.
So something like this

createdTime: {
     $lt: new Date().getTime(),
     $gt: new Date().getTime() - 1000 * 60 * 60 * 24,
},

But like I explained this is not what I want.

Body:
Whenever you have to work with date/time arithmetic then I recommend moment.js library:

createdTime: {
   $lt: moment().endOf('day').subtract(1, 'day').toDate(),
   $gte: moment().startOf('day').subtract(1, 'day').toDate()
},

Alternative libraries are luxon and day.js


问:
Webpack error " ValidationError: Invalid parser object"
After update to webpack 5 I have this error:

```<code>Module not found: ValidationError: Invalid parser object. Json Modules Plugin has been initialized using a parser object that does not match the API schema.- parser has an unknown property 'amd'. These properties are valid:  object { parse? }
</code>```

webpack 5.68.0

答:
My bad Im lost in my code this:

```<code>parser: {
      amd: false,
    },
</code>```

Without this its works

Body:
After update to webpack 5 I have this error:

Module not found: ValidationError: Invalid parser object. Json Modules Plugin has been initialized using a parser object that does not match the API schema.- parser has an unknown property 'amd'. These properties are valid:  object { parse? }

webpack 5.68.0

Body:
My bad Im lost in my code this:

parser: {
      amd: false,
    },

Without this its works


问:
DB2 ERRORCODE=-4229, SQLSTATE=null
I'm getting this error while executing a batch operation.
Use getNextException() to retrieve the exceptions for specific batched elements.ERRORCODE=-4229, SQLSTATE=null

I'm not finding any pointer to proceed with debugging this error.

Appreciating any help!!!

答:
For anyone who is still wondering, try entering a unique record and check if the error still persists?
For me it was because of duplicate entry of a foreign key.</p>

Title: DB2 ERRORCODE=-4229, SQLSTATE=null


问:
How to store output in log file in this case:
```<code>webhook=https://webhook-url

if [[ some_condition ]]; then
curl "some_command..." -d '{"content":"'"success"'"}' $webhook #sends message to discord if condition is met
else
curl "some_command..." -d '{"content":"'"error"'"}' $webhook #sends message to discord if condition isn't met
fi
</code>```

Above bash script successfully sends message to discord but at the same time I want it to store the same message in a log file. Without using webhook, earlier code was as follows:

```<code>if [[ some_condition ]]; then
echo "success" >> file.log
else
echo "error" >> file.log
fi
</code>```

Now I'm not sure how do I include >> file.log command in first script.

答:
Just merge the contents of the if block from the two scripts:</p>
```<code>if [[ some_condition ]]; then
    message="Some 'success' information."
    curl "some_command..." -d '{"content":"$message"}' $webhook #sends message to discord if condition is met
    echo $message >> file.log
else
    message="Some 'error' information."
    curl "some_command..." -d '{"content":"$message"}' $webhook #sends message to discord if condition isn't met
    echo $message >> file.log
fi
</code>```

Body:
webhook=https://webhook-url

if [[ some_condition ]]; then
curl "some_command..." -d '{"content":"'"success"'"}' $webhook #sends message to discord if condition is met
else
curl "some_command..." -d '{"content":"'"error"'"}' $webhook #sends message to discord if condition isn't met
fi

Above bash script successfully sends message to discord but at the same time I want it to store the same message in a log file. Without using webhook, earlier code was as follows:

if [[ some_condition ]]; then
echo "success" >> file.log
else
echo "error" >> file.log
fi

Now I'm not sure how do I include >> file.log command in first script.

Body:
Just merge the contents of the if block from the two scripts:

if [[ some_condition ]]; then
    message="Some 'success' information."
    curl "some_command..." -d '{"content":"$message"}' $webhook #sends message to discord if condition is met
    echo $message >> file.log
else
    message="Some 'error' information."
    curl "some_command..." -d '{"content":"$message"}' $webhook #sends message to discord if condition isn't met
    echo $message >> file.log
fi


问:
Add second facet grid or second discrete y-axis label GGPlot2
Suppose I have this dataframe:

```<code>library(ggplot2)
library(dplyr)
library(readr)
library(magrittr)
library(tidyr)

df2 <- data.frame(tissue = c("Blood", "Nerve", "Stomach", "Liver", "Blood", "Kidney"),
                  qtl = c("e", "s", "e", "e", "s", "s"),
                  gene = c("gene1", "gene1",
                           "gene2", "gene2",
                           "gene3", "gene4"),
                  value = c(0.4, 0.2, 0.1, 0.9, 0.5, 0.3),
                  second_label = c("label1", "label1", "label1","label1",
                                  "label2", "label2"))

</code>```

And I plot it as such:

```<code>ggplot(df2,
       aes(x=tissue, y=qtl,
           size=value))+
  geom_point()+
  facet_grid(rows = vars(gene),
             scales = "free",
             space='free',
             switch = "y")+
  theme(axis.title.x = element_blank(),
        axis.text.x = element_text(size=8,angle = 90, hjust=1, vjust=0.2),
        axis.title.y = element_blank(),
        axis.text.y = element_text(size=8),
        axis.ticks.y = element_blank(),
        axis.line = element_line(color = "black"),
        strip.text.y.left = element_text(size = 8, angle=0),
        strip.background = element_blank(),
        panel.spacing.y = unit(0.5, "lines"),
        strip.placement = "outside",
        panel.background = element_blank(),
        panel.grid.major = element_line(colour = "#ededed", size = 0.5))
</code>```

This code yields the plot below (see first image)

However, I want to add a second facet wrap, being the "loci" and place it on the right side of the figure.

Is this possible? I know in facet_grid, you can do it where one variable is the column and the other is the row, but I haven't seen how to do it where both are rows.

I've looked into adding a secondary y-axis with sec.axis but that seems to only be for continuous variables.

Thanks in advance!

答:
I highly recommend the ggh4x package (github link here), which can handle this issue nicely via nested facets via facet_nested().  Here, you facet according to df2$gene, but indicate the nesting of those facets happens according to df2$qtl.

Here's an example of code that shows you some basic functionality applied to df2.  Note I changed some strip background formatting to make the faceting more clear.  There's a lot of other options that might work better for you in that package.

```<code>p <-
  ggplot(df2, aes(x=tissue, y=qtl, size=value))+
  geom_point()+
  facet_nested(qtl + gene ~ .) +

  theme(axis.title.x = element_blank(),
        axis.text.x = element_text(size=8,angle = 90, hjust=1, vjust=0.2),
        axis.title.y = element_blank(),
        axis.text.y = element_text(size=8),
        axis.ticks.y = element_blank(),
        axis.line = element_line(color = "black"),
        strip.text.y.left = element_text(size = 8, angle=0),
        strip.background = element_rect(fill='white', color="black"),
        panel.spacing.y = unit(0.5, "lines"),
        strip.placement = "outside",
        panel.background = element_blank(),
        panel.grid.major = element_line(colour = "#ededed", size = 0.5))
p
</code>```

Body:
Suppose I have this dataframe:

library(ggplot2)
library(dplyr)
library(readr)
library(magrittr)
library(tidyr)

df2 <- data.frame(tissue = c("Blood", "Nerve", "Stomach", "Liver", "Blood", "Kidney"),
                  qtl = c("e", "s", "e", "e", "s", "s"),
                  gene = c("gene1", "gene1",
                           "gene2", "gene2",
                           "gene3", "gene4"),
                  value = c(0.4, 0.2, 0.1, 0.9, 0.5, 0.3),
                  second_label = c("label1", "label1", "label1","label1",
                                  "label2", "label2"))

And I plot it as such:

ggplot(df2,
       aes(x=tissue, y=qtl,
           size=value))+
  geom_point()+
  facet_grid(rows = vars(gene),
             scales = "free",
             space='free',
             switch = "y")+
  theme(axis.title.x = element_blank(),
        axis.text.x = element_text(size=8,angle = 90, hjust=1, vjust=0.2),
        axis.title.y = element_blank(),
        axis.text.y = element_text(size=8),
        axis.ticks.y = element_blank(),
        axis.line = element_line(color = "black"),
        strip.text.y.left = element_text(size = 8, angle=0),
        strip.background = element_blank(),
        panel.spacing.y = unit(0.5, "lines"),
        strip.placement = "outside",
        panel.background = element_blank(),
        panel.grid.major = element_line(colour = "#ededed", size = 0.5))

This code yields the plot below (see first image)

However, I want to add a second facet wrap, being the "loci" and place it on the right side of the figure.

Is this possible? I know in facet_grid, you can do it where one variable is the column and the other is the row, but I haven't seen how to do it where both are rows.

I've looked into adding a secondary y-axis with sec.axis but that seems to only be for continuous variables.

Thanks in advance!

Body:
I highly recommend the ggh4x package (github link here), which can handle this issue nicely via nested facets via facet_nested().  Here, you facet according to df2$gene, but indicate the nesting of those facets happens according to df2$qtl.

Here's an example of code that shows you some basic functionality applied to df2.  Note I changed some strip background formatting to make the faceting more clear.  There's a lot of other options that might work better for you in that package.

p <-
  ggplot(df2, aes(x=tissue, y=qtl, size=value))+
  geom_point()+
  facet_nested(qtl + gene ~ .) +

  theme(axis.title.x = element_blank(),
        axis.text.x = element_text(size=8,angle = 90, hjust=1, vjust=0.2),
        axis.title.y = element_blank(),
        axis.text.y = element_text(size=8),
        axis.ticks.y = element_blank(),
        axis.line = element_line(color = "black"),
        strip.text.y.left = element_text(size = 8, angle=0),
        strip.background = element_rect(fill='white', color="black"),
        panel.spacing.y = unit(0.5, "lines"),
        strip.placement = "outside",
        panel.background = element_blank(),
        panel.grid.major = element_line(colour = "#ededed", size = 0.5))
p


问:
JBoss EAP 7: Disable tag pooling outside standalone.xml
I'm migrating a legacy application from Weblogic to JBoss EAP 7. The application contains custom tags which were not created with tag pooling in mind (e.g. they have internal state not properly cleaned up in doEndTag).

According to RedHat docs https://access.redhat.com/solutions/1186363, in EAP 6 there was a parameter to be set in web.xml:

```<code><servlet>
  ...
  <init-param>
     <param-name>enablePooling</param-name>
     <param-value>false</param-value>
  </init-param>
  ...
</servlet>
</code>```

Unfortunately, looks like in EAP 7 this is only doable by configuring the undertow subsystem.

```<code><subsystem xmlns="urn:jboss:domain:undertow:4.0">
    ...
    <servlet-container name="default">
        <jsp-config tag-pooling="false"/>
        <websockets/>
    </servlet-container>
</code>```

My problem is my application needs to run on a Docker image that I cannot modify nor request to modify, since it's intended to be shared among different applications which might perfectly work with tag pooling. Hence editing standalone.xml or other server-wide configuration files is not feasible.
What I can do:

I provide the war/ear file, so I can modify anything inside it (e.g. web.xml, jboss-web.xml, java code, ...). The EAP 6 solution would be perfect if it worked on EAP 7

I can edit system properties

I can edit environment variables

Is there any way to disable tag-pooling given these constraints?

答:
You can modify the standandalone.xml only for the application with the problem through its own Dockerfile:

disable.jboss.tag-pooling.cli

```<code>embed-server --server-config=${JBOSS_PROFILE}
command-timeout set 60

echo #### Disable JSP tag-pooling
if (outcome == success) of /subsystem=undertow/servlet-container=default/setting=jsp:write-attribute(name=tag-pooling, value=false)
   echo tag-pooling was set to false
end-if

stop-embedded-server
quit
</code>```

Dockerfile

```<code>ENV CLI_ARGS="--timeout=30000 --properties=/tmp/cli.env.properties --echo-command"
RUN echo JBOSS_PROFILE=standalone.xml > /tmp/cli.env.properties

COPY --chown=jboss:jboss "disable.jboss.tag-pooling.cli" "/tmp/"
RUN $JBOSS_HOME/bin/jboss-cli.sh --file=/tmp/disable.jboss.tag-pooling.cli $CLI_ARGS
</code>```

Body:
I'm migrating a legacy application from Weblogic to JBoss EAP 7. The application contains custom tags which were not created with tag pooling in mind (e.g. they have internal state not properly cleaned up in doEndTag).

According to RedHat docs https://access.redhat.com/solutions/1186363, in EAP 6 there was a parameter to be set in web.xml:

<servlet>
  ...
  <init-param>
     <param-name>enablePooling</param-name>
     <param-value>false</param-value>
  </init-param>
  ...
</servlet>

Unfortunately, looks like in EAP 7 this is only doable by configuring the undertow subsystem.

<subsystem xmlns="urn:jboss:domain:undertow:4.0">
    ...
    <servlet-container name="default">
        <jsp-config tag-pooling="false"/>
        <websockets/>
    </servlet-container>

My problem is my application needs to run on a Docker image that I cannot modify nor request to modify, since it's intended to be shared among different applications which might perfectly work with tag pooling. Hence editing standalone.xml or other server-wide configuration files is not feasible.
What I can do:

I provide the war/ear file, so I can modify anything inside it (e.g. web.xml, jboss-web.xml, java code, ...). The EAP 6 solution would be perfect if it worked on EAP 7

I can edit system properties

I can edit environment variables

Is there any way to disable tag-pooling given these constraints?

Body:
You can modify the standandalone.xml only for the application with the problem through its own Dockerfile:

disable.jboss.tag-pooling.cli

embed-server --server-config=${JBOSS_PROFILE}
command-timeout set 60

echo #### Disable JSP tag-pooling
if (outcome == success) of /subsystem=undertow/servlet-container=default/setting=jsp:write-attribute(name=tag-pooling, value=false)
   echo tag-pooling was set to false
end-if

stop-embedded-server
quit

Dockerfile

ENV CLI_ARGS="--timeout=30000 --properties=/tmp/cli.env.properties --echo-command"
RUN echo JBOSS_PROFILE=standalone.xml > /tmp/cli.env.properties

COPY --chown=jboss:jboss "disable.jboss.tag-pooling.cli" "/tmp/"
RUN $JBOSS_HOME/bin/jboss-cli.sh --file=/tmp/disable.jboss.tag-pooling.cli $CLI_ARGS


问:
PHP foreach loop to populate dropdown list with values from an array of arrays
I have an array of an arrays created using the following code. I'm trying to get this to loop through and populate a dropdown list.

```<code>$names = $db->fetchAll("select `name` from `classes`");
</code>```

This is what is stored in the $names variable.

Array ( [0] => Array ( [name] => Web Design ) [1] => Array ( [name] =>
  Art History ) [2] => Array ( [name] => Gym ) [3] => Array ( [name] =>
  English ) [4] => Array ( [name] => Biology ) [5] => Array ( [name] =>
  3D Animation ) [6] => Array ( [name] => Tech Disc ) [7] => Array (
  [name] => Math ) [8] => Array ( [name] => Dance ) [9] => Array (
  [name] => Video Production ) [10] => Array ( [name] => Home Ec ) [11]
  => Array ( [name] => Government ) [12] => Array ( [name] => Physics ) )

I have this dropdown list created and it work, but it is hand coded for each value in the array. I want to modify this so it 'loops' through all results in the array to create the dropdown.

```<code><label for="per1"></label>
<select name="per1" id="per1">
    <option selected="selected">Choose one</option>
    <option value="<?php echo $names[0]['name'];?>"><?php echo $names[0]['name'];?></option>
    <option value="<?php echo $names[1]['name'];?>"><?php echo $names[1]['name'];?></option>
    <option value="<?php echo $names[2]['name'];?>"><?php echo $names[2]['name'];?></option>
    <option value="<?php echo $names[3]['name'];?>"><?php echo $names[3]['name'];?></option>
    <option value="<?php echo $names[4]['name'];?>"><?php echo $names[4]['name'];?></option>
    <option value="<?php echo $names[5]['name'];?>"><?php echo $names[5]['name'];?></option>
    <option value="<?php echo $names[6]['name'];?>"><?php echo $names[6]['name'];?></option>
    <option value="<?php echo $names[7]['name'];?>"><?php echo $names[7]['name'];?></option>
    <option value="<?php echo $names[8]['name'];?>"><?php echo $names[8]['name'];?></option>
    <option value="<?php echo $names[9]['name'];?>"><?php echo $names[9]['name'];?></option>
    <option value="<?php echo $names[10]['name'];?>"><?php echo $names[10]['name'];?></option>
    <option value="<?php echo $names[11]['name'];?>"><?php echo $names[11]['name'];?></option>
    <option value="<?php echo $names[12]['name'];?>"><?php echo $names[12]['name'];?></option>
</select>
</code>```

Can someone please help?

答:
loop through the array [1] and get the value of the key 'name' display it in the dropdown</p>
```<code>foreach($response['items'] as $key => $value)
{
   echo '<option value="'.$value['name'].'">'.$value['name'].'</option>';
}
</code>```

Body:
I have an array of an arrays created using the following code. I'm trying to get this to loop through and populate a dropdown list.

$names = $db->fetchAll("select `name` from `classes`");

This is what is stored in the $names variable.

Array ( [0] => Array ( [name] => Web Design ) [1] => Array ( [name] =>
  Art History ) [2] => Array ( [name] => Gym ) [3] => Array ( [name] =>
  English ) [4] => Array ( [name] => Biology ) [5] => Array ( [name] =>
  3D Animation ) [6] => Array ( [name] => Tech Disc ) [7] => Array (
  [name] => Math ) [8] => Array ( [name] => Dance ) [9] => Array (
  [name] => Video Production ) [10] => Array ( [name] => Home Ec ) [11]
  => Array ( [name] => Government ) [12] => Array ( [name] => Physics ) )

I have this dropdown list created and it work, but it is hand coded for each value in the array. I want to modify this so it 'loops' through all results in the array to create the dropdown.

<select name="per1" id="per1">
    <option selected="selected">Choose one</option>
    <option value="<?php echo $names[0]['name'];?>"><?php echo $names[0]['name'];?></option>
    <option value="<?php echo $names[1]['name'];?>"><?php echo $names[1]['name'];?></option>
    <option value="<?php echo $names[2]['name'];?>"><?php echo $names[2]['name'];?></option>
    <option value="<?php echo $names[3]['name'];?>"><?php echo $names[3]['name'];?></option>
    <option value="<?php echo $names[4]['name'];?>"><?php echo $names[4]['name'];?></option>
    <option value="<?php echo $names[5]['name'];?>"><?php echo $names[5]['name'];?></option>
    <option value="<?php echo $names[6]['name'];?>"><?php echo $names[6]['name'];?></option>
    <option value="<?php echo $names[7]['name'];?>"><?php echo $names[7]['name'];?></option>
    <option value="<?php echo $names[8]['name'];?>"><?php echo $names[8]['name'];?></option>
    <option value="<?php echo $names[9]['name'];?>"><?php echo $names[9]['name'];?></option>
    <option value="<?php echo $names[10]['name'];?>"><?php echo $names[10]['name'];?></option>
    <option value="<?php echo $names[11]['name'];?>"><?php echo $names[11]['name'];?></option>
    <option value="<?php echo $names[12]['name'];?>"><?php echo $names[12]['name'];?></option>
</select>

Can someone please help?

Body:
loop through the array [1] and get the value of the key 'name' display it in the dropdown

foreach($response['items'] as $key => $value)
{
   echo '<option value="'.$value['name'].'">'.$value['name'].'</option>';
}


问:
Best way to download a file from a Laravel API with React
I'm trying to use Laravel as a file server (protected for authorized user only) but I struggle with an issue.

My Laravel API delivers large files (90Mo +-) to my React app.

To send my file from Laravel, I used this:

return Storage::disk('public')->download('myFile.zip');

And I download the file in React with Axios + FileSaver:

```<code> axios
      .get("https://url/to/api/", {
        method: "GET",
        mode: "cors",
        headers: {
          Authorization: `Bearer ${token}`,
          "Access-Control-Allow-Origin": true,
          Accept: "application/zip",
        },
        responseType: "arraybuffer",
      })
      .then(response => {
        const blob = new Blob([response.data], {
          type: "application/zip",
        });

        saveAs(blob, "myFile.zip");

      })
      .catch(err => {
        console.log(err);
      });
</code>```

My issue is that one I clicked on the button that trigger the download, nothing happen until the file is fully downloaded in background THEN I can save or read the file as a "normal" download.

For small files it's not a big issue but when my file is like 90Mo + a bad connection and you can wait during a long moment in front of a screen doing nothing.

Any advices ?

答:
Check that: https://www.npmjs.com/package/js-file-download

You should trigger FileDownload before it completes the download itself.
Related: How to download files using axios

Body:
I'm trying to use Laravel as a file server (protected for authorized user only) but I struggle with an issue.

My Laravel API delivers large files (90Mo +-) to my React app.

To send my file from Laravel, I used this:

return Storage::disk('public')->download('myFile.zip');

And I download the file in React with Axios + FileSaver:

 axios
      .get("https://url/to/api/", {
        method: "GET",
        mode: "cors",
        headers: {
          Authorization: `Bearer ${token}`,
          "Access-Control-Allow-Origin": true,
          Accept: "application/zip",
        },
        responseType: "arraybuffer",
      })
      .then(response => {
        const blob = new Blob([response.data], {
          type: "application/zip",
        });

        saveAs(blob, "myFile.zip");

      })
      .catch(err => {
        console.log(err);
      });

My issue is that one I clicked on the button that trigger the download, nothing happen until the file is fully downloaded in background THEN I can save or read the file as a "normal" download.

For small files it's not a big issue but when my file is like 90Mo + a bad connection and you can wait during a long moment in front of a screen doing nothing.

Any advices ?


问:
Installing Stripe dependencies in Firebase CLI for a Flutter app
I am trying to integrate Stripe into my Flutter app.

I have finished the Flutter part of it and now I am trying to use Firebase Cloud functions to manage the server side part of the Stripe payment.

I have installed Firebase CLI on my Mac.

Then I have open the Mac terminal and put the command

```<code>firebase init
</code>```

Then I have selected the Functions option, then I have selected an existing project, then I have selected JavaScript for language, then I have selected YES to install the dependencies with npm.

Then I have put cd functions to enter into the functions folder.

Inside the functions folder I have put npm install stripe --save

but an error is shown:

I would like to know what am I missing in order to install Stripe dependencies to be use with my Firebase project.

答:
It seems that you need to install Node.js and the npm command line interface.

The previous steps described in your question are the correct ones.

Body:
I am trying to integrate Stripe into my Flutter app.

I have finished the Flutter part of it and now I am trying to use Firebase Cloud functions to manage the server side part of the Stripe payment.

I have installed Firebase CLI on my Mac.

Then I have open the Mac terminal and put the command

firebase init

Then I have selected the Functions option, then I have selected an existing project, then I have selected JavaScript for language, then I have selected YES to install the dependencies with npm.

Then I have put cd functions to enter into the functions folder.

Inside the functions folder I have put npm install stripe --save

but an error is shown:

I would like to know what am I missing in order to install Stripe dependencies to be use with my Firebase project.


问:
What is the advantage of using a Materialized View over a base table in Amazon Redshift?
Conceptually, I understand that materialized views are static representations of computed values, but I don't understand how that is functionally different from creating a table that contains the same pre-computed data. I would think a table could be even more performant since one could add sortkeys.</p>

答: In short, MV is a one time operation accompanied by REFRESH whereas Table CTAS would be DROP & Recreate or Truncate (but insert after truncate would be slower as compared to Drop and recreate ) option. The best part to choose MV is it allows 2 modes Incremental and Full Load in redshift but Incremental is restricted to a huge level no complex query/Joins/Order by/Limit/Aggregations (only basic count,max etc allowed) but still MVs becomes preferable as it has the other mode which recompute full load again using just a same REFRESH command. One sole aspect that is useful to choose CTAS over MVs is Distribution Style AUTO on Table vs Not Such Auto option in MVs meaning it will not allow redshift capability to self decide Distribution Style whenever needed.</p>


问:
Apple Mach-O Linker (id) Error
I have an error below:

```<code>ld /Volumes/Data/Library/Developer/Xcode/DerivedData/uniText-cgynaitlevdrajfeoaldwldehaft/Build/Products/Debug-iphonesimulator/uniText.app/uniText normal i386
    cd "/Volumes/Data/Documents/XCode Projects/Trans SMS"
    setenv MACOSX_DEPLOYMENT_TARGET 10.6
    setenv PATH "/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
    /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/llvm-gcc-4.2 -arch i386 -isysroot /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.3.sdk -L/Volumes/Data/Library/Developer/Xcode/DerivedData/uniText-cgynaitlevdrajfeoaldwldehaft/Build/Products/Debug-iphonesimulator -F/Volumes/Data/Library/Developer/Xcode/DerivedData/uniText-cgynaitlevdrajfeoaldwldehaft/Build/Products/Debug-iphonesimulator -filelist /Volumes/Data/Library/Developer/Xcode/DerivedData/uniText-cgynaitlevdrajfeoaldwldehaft/Build/Intermediates/uniText.build/Debug-iphonesimulator/uniText.build/Objects-normal/i386/uniText.LinkFileList -mmacosx-version-min=10.6 -Xlinker -objc_abi_version -Xlinker 2 -framework SystemConfiguration -framework MessageUI -framework AddressBook -framework AddressBookUI -framework CoreTelephony -lsqlite3.0 -framework UIKit -framework Foundation -framework CoreGraphics -o /Volumes/Data/Library/Developer/Xcode/DerivedData/uniText-cgynaitlevdrajfeoaldwldehaft/Build/Products/Debug-iphonesimulator/uniText.app/uniText

ld: duplicate symbol _OBJC_IVAR_$_FMDatabase.databasePath in /Volumes/Data/Library/Developer/Xcode/DerivedData/uniText-cgynaitlevdrajfeoaldwldehaft/Build/Intermediates/uniText.build/Debug-iphonesimulator/uniText.build/Objects-normal/i386/FMDatabase-566DC6D59187887D.o and /Volumes/Data/Library/Developer/Xcode/DerivedData/uniText-cgynaitlevdrajfeoaldwldehaft/Build/Intermediates/uniText.build/Debug-iphonesimulator/uniText.build/Objects-normal/i386/FMDatabase-566DC6D59187887D.o for architecture i386
collect2: ld returned 1 exit status
Command /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/llvm-gcc-4.2 failed with exit code 1
</code>```

Could someone help me out?
It used to work properly before.
I have no idea what I have changed in the project sources.
But I am sure that I never changed anything in that FMDatabase.h and .m.

答: Check if you import framework which required.</p>

Title: Apple Mach-O Linker (id) Error

Body:
I have an error below:

ld /Volumes/Data/Library/Developer/Xcode/DerivedData/uniText-cgynaitlevdrajfeoaldwldehaft/Build/Products/Debug-iphonesimulator/uniText.app/uniText normal i386
    cd "/Volumes/Data/Documents/XCode Projects/Trans SMS"
    setenv MACOSX_DEPLOYMENT_TARGET 10.6
    setenv PATH "/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
    /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/llvm-gcc-4.2 -arch i386 -isysroot /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.3.sdk -L/Volumes/Data/Library/Developer/Xcode/DerivedData/uniText-cgynaitlevdrajfeoaldwldehaft/Build/Products/Debug-iphonesimulator -F/Volumes/Data/Library/Developer/Xcode/DerivedData/uniText-cgynaitlevdrajfeoaldwldehaft/Build/Products/Debug-iphonesimulator -filelist /Volumes/Data/Library/Developer/Xcode/DerivedData/uniText-cgynaitlevdrajfeoaldwldehaft/Build/Intermediates/uniText.build/Debug-iphonesimulator/uniText.build/Objects-normal/i386/uniText.LinkFileList -mmacosx-version-min=10.6 -Xlinker -objc_abi_version -Xlinker 2 -framework SystemConfiguration -framework MessageUI -framework AddressBook -framework AddressBookUI -framework CoreTelephony -lsqlite3.0 -framework UIKit -framework Foundation -framework CoreGraphics -o /Volumes/Data/Library/Developer/Xcode/DerivedData/uniText-cgynaitlevdrajfeoaldwldehaft/Build/Products/Debug-iphonesimulator/uniText.app/uniText

ld: duplicate symbol _OBJC_IVAR_$_FMDatabase.databasePath in /Volumes/Data/Library/Developer/Xcode/DerivedData/uniText-cgynaitlevdrajfeoaldwldehaft/Build/Intermediates/uniText.build/Debug-iphonesimulator/uniText.build/Objects-normal/i386/FMDatabase-566DC6D59187887D.o and /Volumes/Data/Library/Developer/Xcode/DerivedData/uniText-cgynaitlevdrajfeoaldwldehaft/Build/Intermediates/uniText.build/Debug-iphonesimulator/uniText.build/Objects-normal/i386/FMDatabase-566DC6D59187887D.o for architecture i386
collect2: ld returned 1 exit status
Command /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/llvm-gcc-4.2 failed with exit code 1

Could someone help me out?
It used to work properly before.
I have no idea what I have changed in the project sources.
But I am sure that I never changed anything in that FMDatabase.h and .m.


答:
Since you can pop columns, you can take transpose of the dataframe and pop its columns, ie. the rows of the original df like this. Here is the original df.

```<code>    import numpy as np
df = pd.DataFrame(np.random.randint(0, 10, size=(3, 3)), columns = ['a', 'b', 'c'])

print(df)
   a  b  c
0  4  9  4
1  5  5  8
2  5  7  4
</code>```

Then you take transpose of it and pop column 0 which is the row 0 of the original df.

```<code>df_t = df.T
popped_row = df_t.pop(0)
</code>```

Now you have the popped row

```<code>print(popped_row)
a    4
b    9
c    4
Name: 0, dtype: int32
</code>```

And then you have the original dataframe without the first row.

```<code>df = df_t.T

print(df)
   a  b  c
1  5  5  8
2  5  7  4
</code>```

Title: How to pop rows from a dataframe?

Body:
I found the documentation for pandas.DataFrame.pop, but after trying it and examining the source code, it does not seem to do what I want.

If I make a dataframe like this:

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(10,6))
# Make a few areas have NaN values
df.iloc[1:3,1] = np.nan
df.iloc[5,3] = np.nan
df.iloc[7:9,5] = np.nan

>>> df
          0         1         2         3         4         5
0  0.772762 -0.442657  1.245988  1.102018 -0.740836  1.685598
1 -0.387922       NaN -1.215723 -0.106875  0.499110  0.338759
2  0.567631       NaN -0.353032 -0.099011 -0.698925 -1.348966
3  1.320849  1.084405 -1.296177  0.681111 -1.941855 -0.950346
4 -0.026818 -1.933629 -0.693964  1.116673  0.392217  1.280808
5 -1.249192 -0.035932 -1.330916       NaN -0.135720 -0.506016
6  0.406344  1.416579  0.122019  0.648851 -0.305359 -1.253580
7 -0.092440 -0.243593  0.468463 -1.689485  0.667804       NaN
8 -0.110819 -0.627777 -0.302116  0.630068  2.567923       NaN
9  1.884069 -0.393420 -0.950275  0.151182 -1.122764  0.502117

If I want to remove selected rows and assign them to a separate object in one step, I would want a pop behavior, like this:

# rows in column 5 which have NaN values
>>> df[df[5].isnull()].index
Int64Index([7, 8], dtype='int64')

# remove them from the dataframe, assign them to a separate object
>>> nan_rows = df.pop(df[df[5].isnull()].index)

However, this does not appear to be supported. Instead, it seems like I am forced to do this in two separate steps, which seems a bit inelegant.

# get the NaN rows
>>> nan_rows = df[df[5].isnull()]

>>> nan_rows
          0         1         2         3         4   5
7 -0.092440 -0.243593  0.468463 -1.689485  0.667804 NaN
8 -0.110819 -0.627777 -0.302116  0.630068  2.567923 NaN

# remove from orignal df
>>> df = df.drop(nan_rows.index)

>>> df
          0         1         2         3         4         5
0  0.772762 -0.442657  1.245988  1.102018 -0.740836  1.685598
1 -0.387922       NaN -1.215723 -0.106875  0.499110  0.338759
2  0.567631       NaN -0.353032 -0.099011 -0.698925 -1.348966
3  1.320849  1.084405 -1.296177  0.681111 -1.941855 -0.950346
4 -0.026818 -1.933629 -0.693964  1.116673  0.392217  1.280808
5 -1.249192 -0.035932 -1.330916       NaN -0.135720 -0.506016
6  0.406344  1.416579  0.122019  0.648851 -0.305359 -1.253580
9  1.884069 -0.393420 -0.950275  0.151182 -1.122764  0.502117

Is there a one-step method built-in? Or is this the way you're 'supposed' to do it?

Body:
Since you can pop columns, you can take transpose of the dataframe and pop its columns, ie. the rows of the original df like this. Here is the original df.

    import numpy as np
df = pd.DataFrame(np.random.randint(0, 10, size=(3, 3)), columns = ['a', 'b', 'c'])

print(df)
   a  b  c
0  4  9  4
1  5  5  8
2  5  7  4

Then you take transpose of it and pop column 0 which is the row 0 of the original df.

df_t = df.T
popped_row = df_t.pop(0)

Now you have the popped row

print(popped_row)
a    4
b    9
c    4
Name: 0, dtype: int32

And then you have the original dataframe without the first row.

df = df_t.T

print(df)
   a  b  c
1  5  5  8
2  5  7  4


问:
Syntax error in VS Code in python, while the same code is running well in pycharm
You can see the error in this image:

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

I am sure this is some kind of interpreter problem, but I couldn't find the solution. I am on mac environment.

答:
maybe deploy it on a bash terminal and to deploy it write:
python func.py


问:
Head is getting reversed in a linked list for a palindrome validation algo
I am trying to write an algorithm that checks if an input LinkedList is a palindrome or not. My algorithm is as follows:

Set a dummy node to point to the head of the input linkedList

Use a handler to store the reversed linkedlist

Run a loop to compare the values from front and back

My error: I know that the algorithm is wrong, because the output that I get seems to say that my original head is pointing in the wrong direction. I cannot figure out why, since I have used handler nodes while reversing as well.

The code is as follows:

class Solution {
    public boolean isPalindrome(ListNode head) {
        if(head==null) return true;
        ListNode dummy = head;
        ListNode MatchList = null;
        MatchList=reverseList(head);
        while(dummy!=null)
        {
            if(dummy.val!=MatchList.val)
            {return false;}
            MatchList=MatchList.next;
            dummy=dummy.next;
        }
        return true;
    }

    public ListNode reverseList(ListNode head) {
        ListNode dummy, newHead;
        newHead=head;
        ListNode another=newHead;
        ListNode prev=null;
        while(another!=null)
        {
            dummy=another.next;
            another.next=prev;
            prev=another;
            another=dummy;
        }
        return prev;
    }
}
```

答:
The problem in your attempt is that when you reverse the list, it happens to that list. Yet your code deals with it as if it is a second list, independent from the first list. But because it is not, the head node has become the tail, and so after reverseList has been called, head.next (i.e. dummy.next) is going to be null.

A simple idea would be to change reverseList so that it creates a new list, calling the ListNode constructor for each node it encounters, but then linking them in the opposite direction.

This is however not an ideal solution, as it needs O(n) auxiliary space.

There is the following "trick" you can apply:

Find the middle node of the list (or if the size is even, the first one of the second half).

Reverse the list that starts at that node, i.e. reverse the second half of the list

Now you can walk in both halves and compare the values in tandem.

To make that work, here is  a function you could use:

```<code>public ListNode middleNode(ListNode head) {
    ListNode fast = head;
    while (fast != null && fast.next != null) {
        head = head.next;
        fast = fast.next.next;
    }
    return head;
}
</code>```

And now you can do:

```<code>public boolean isPalindrome(ListNode head) {
    if (head == null) return true;
    ListNode mid = middleNode(head);
    ListNode tail = reverseList(mid);
    while (tail != null) {
        if (head.val != tail.val) return false;
        tail = tail.next;
        head = head.next;
    }
    return true;
}
</code>```

Body:
The problem in your attempt is that when you reverse the list, it happens to that list. Yet your code deals with it as if it is a second list, independent from the first list. But because it is not, the head node has become the tail, and so after reverseList has been called, head.next (i.e. dummy.next) is going to be null.

A simple idea would be to change reverseList so that it creates a new list, calling the ListNode constructor for each node it encounters, but then linking them in the opposite direction.

This is however not an ideal solution, as it needs O(n) auxiliary space.

There is the following "trick" you can apply:

Find the middle node of the list (or if the size is even, the first one of the second half).

Reverse the list that starts at that node, i.e. reverse the second half of the list

Now you can walk in both halves and compare the values in tandem.

To make that work, here is  a function you could use:

public ListNode middleNode(ListNode head) {
    ListNode fast = head;
    while (fast != null && fast.next != null) {
        head = head.next;
        fast = fast.next.next;
    }
    return head;
}

And now you can do:

public boolean isPalindrome(ListNode head) {
    if (head == null) return true;
    ListNode mid = middleNode(head);
    ListNode tail = reverseList(mid);
    while (tail != null) {
        if (head.val != tail.val) return false;
        tail = tail.next;
        head = head.next;
    }
    return true;
}


问:
Pseudo color plot of random lattice in python
I have a list that I use to represent a lattice:

```<code>lattice = [[np.array([0., 0.]), 1.5], [np.array([5., 0.]), 2], [np.array([10., 0.]), 0.7]]
</code>```

For each component in the list, the first array represents its location, and the second number represents a certain rotational degree of the component. For example, this lattice I listed above have three components: one located at (0, 0) rotated 1.5 pi; one located at (5, 0) rotated 2 pi; one located at (10, 0) rotated 0.7 pi.

To illustrate it better, the lattices I am looking at are 2D. In the graphs below, each arrow shows one component, I set the system up such that the components don't overlap with each other (thank you Johan for the notes!)

lattice visualization 1
lattice visualization 2

I want to generate a pseudo color plot that will allow me to visualize the rotation of each component with color at its specific location.

For example, at each location I:

generate a circle,

color the circle based on the rotation angle (second value in the array) using a color bar(color darker as the value increase).

Is there any possible way to do this in python?

Thank you so much for reading this post and I hope you have a great day no matter you reply or not! Thank you thank you thank you!

答: You mean that you want a system in which you will pass the coordinates and rotated angles, then draw a circle at a specific location with color. You can achieve through turtle in python, in which you start the turtle at a specific position and then move the turtle according to your angle, and draw the circle and set the color that you want.</p>

Body:
I have a list that I use to represent a lattice:

lattice = [[np.array([0., 0.]), 1.5], [np.array([5., 0.]), 2], [np.array([10., 0.]), 0.7]]

For each component in the list, the first array represents its location, and the second number represents a certain rotational degree of the component. For example, this lattice I listed above have three components: one located at (0, 0) rotated 1.5 pi; one located at (5, 0) rotated 2 pi; one located at (10, 0) rotated 0.7 pi.

To illustrate it better, the lattices I am looking at are 2D. In the graphs below, each arrow shows one component, I set the system up such that the components don't overlap with each other (thank you Johan for the notes!)

lattice visualization 1
lattice visualization 2

I want to generate a pseudo color plot that will allow me to visualize the rotation of each component with color at its specific location.

For example, at each location I:

generate a circle,

color the circle based on the rotation angle (second value in the array) using a color bar(color darker as the value increase).

Is there any possible way to do this in python?

Thank you so much for reading this post and I hope you have a great day no matter you reply or not! Thank you thank you thank you!


问:
Unable to identify Button in hybrid page in android app appium
I have tried to identify 'Send' button but Appium doesn't shown source of that page. This page is a webpage in hybrid android app. Is there any way to get source of this button and verify/inspect it?

I have tried with chrome://inspect/#devices and able to inspect this button in Developer tools but don't know where verify? This is what DOM has inspected.

<button id="btnSaveForm" type="button" ng-click="submitForm(1)" class="btn btn-danger" ng-disabled="isXhrPending() || mainCtrl.isAttachUploading">Send</button>

What could be the Xpath of this and how do I verify it?

答:
You can use either of the following xpath based locator strategies:

Using XPATH 1:

```<code>//button[@class='btn btn-danger' and @id='btnSaveForm'][text()='Send']
</code>```

Using XPATH 2:

```<code>//button[@class='btn btn-danger' and @id='btnSaveForm'][starts-with(@ng-click, 'submitForm') and text()='Send']
</code>```

Body:
You can use either of the following xpath based locator strategies:

Using XPATH 1:

//button[@class='btn btn-danger' and @id='btnSaveForm'][text()='Send']

Using XPATH 2:

//button[@class='btn btn-danger' and @id='btnSaveForm'][starts-with(@ng-click, 'submitForm') and text()='Send']


问:
How to Pass the data given in UITextField to another variable on another class
So i have a UITextField named apiTextField and a function of the saveButton :

func saveButton(_ sender: Any) {
}
I want when the user writes to the UITextField and press the saveButton that text the user wrote be passed to a variable which is called var baseURL:String? in another class.

I didn't find anything related to UITextField so i decided to make this question, another similar one is 10 years old!.

答:
```<code>var anotherClass = AnotherClass()

func saveButton(_ sender: Any) {
    guard let text = apiTextField.text, !text.isEmpty else { return }
    anotherClass.baseURL = text
}
</code>```

Is that what you are looking for?

Body:
var anotherClass = AnotherClass()

func saveButton(_ sender: Any) {
    guard let text = apiTextField.text, !text.isEmpty else { return }
    anotherClass.baseURL = text
}

Is that what you are looking for?