问:
How to create a new vector from inputs in a list of vectors?

How could I make another column called "Purpose" that takes in the name of these variables if their input is "Yes"?
Note: there are observations that don't have a "Yes" input at all.

Thankfully, I already have working code:

```<code>CD$PURPOSE <- ifelse(CD$NEW_CAR == "Yes", "New_Car",
                     ifelse(CD$USED_CAR == "Yes", "Used_Car",
                            ifelse(CD$FURNITURE == "Yes", "Furniture",
                                   ifelse(CD$`RADIO/TV` == "Yes", "Radio/TV",
                                          ifelse(CD$EDUCATION == "Yes", "Education",
                                                 ifelse(CD$RETRAINING == "Yes", "Retraining", "None"))))))
</code>```

I would, however, prefer to use something else. My gut instinct says that this isn't best practice.

Here is an unfinished attempt which throws an error:

```<code>PurposeCols <- c("NEW_CAR", "USED_CAR", "FURNITURE", "RADIO/TV", "EDUCATION", "RETRAINING")
Purpose <- vector(mode="character", length=1000)
possible_i= 1:1000

for (1:1000){
for (i in PurposeCols){
  if (CD[,i] == "Yes") {
    Purpose[i] = "Yes"
   }

  }
}
</code>```

The reason I want to change the code is that I realize I could potentially have many more variables that I would need to do a similar process on.

Thank you.

Body:
How could I make another column called "Purpose" that takes in the name of these variables if their input is "Yes"?
Note: there are observations that don't have a "Yes" input at all.

Thankfully, I already have working code:

CD$PURPOSE <- ifelse(CD$NEW_CAR == "Yes", "New_Car",
                     ifelse(CD$USED_CAR == "Yes", "Used_Car",
                            ifelse(CD$FURNITURE == "Yes", "Furniture",
                                   ifelse(CD$`RADIO/TV` == "Yes", "Radio/TV",
                                          ifelse(CD$EDUCATION == "Yes", "Education",
                                                 ifelse(CD$RETRAINING == "Yes", "Retraining", "None"))))))

I would, however, prefer to use something else. My gut instinct says that this isn't best practice.

Here is an unfinished attempt which throws an error:

PurposeCols <- c("NEW_CAR", "USED_CAR", "FURNITURE", "RADIO/TV", "EDUCATION", "RETRAINING")
Purpose <- vector(mode="character", length=1000)
possible_i= 1:1000

for (1:1000){
for (i in PurposeCols){
  if (CD[,i] == "Yes") {
    Purpose[i] = "Yes"
   }

  }
}

The reason I want to change the code is that I realize I could potentially have many more variables that I would need to do a similar process on.

Thank you.


来源: stackexchange

问:
Combine numpy array with TfidfVectorizer as a joint feature matrix in SKLearn
I have a dataset input, which is a list of ~40000 letters (that are represented as strings).

With SKLearn, I first used a TfidfVectorizer to create a TF-IDF matrix representation1:

```<code>import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
import sklearn.pipeline

vectorizer = TfidfVectorizer(lowercase=False)
representation1 = vectorizer.fit_transform(input)  # TFIDF representation
</code>```

Now, I want to manually add one feature representation2 for every letter. This feature should tell the amount of different words compared to all words in a specific letter/string:

```<code>count_vectorizer = CountVectorizer()
sum_words = np.sum(count_vectorizer.fit_transform(input).toarray(), axis=-1)
sum_different_words = np.count_nonzero(count_vectorizer.fit_transform(input).toarray(), axis=-1)
representation2 = np.divide(sum_different_words, sum_words)  # percentage of different words
</code>```

The array representation2 is now an array of shape (39077,) (as expected). I now want to combine representation1 and representation2 into one feature vector representation.

I read about using FeatureUnion to combine two kinds of features in SKLearn, but I am not sure how to correctly use the Numpy array representation2as a feature here. I tried:

```<code>union = sklearn.pipeline.make_union([representation1, representation2])
</code>```

But now I can't use e.g. union.get_feature_names_out(), since it throws: AttributeError: Transformer list (type list) does not provide get_feature_names_out.

What did I understand incorrectly here?

ContentLicense: CC BY-SA 4.0

Body:
I have a dataset input, which is a list of ~40000 letters (that are represented as strings).

With SKLearn, I first used a TfidfVectorizer to create a TF-IDF matrix representation1:

import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
import sklearn.pipeline

vectorizer = TfidfVectorizer(lowercase=False)
representation1 = vectorizer.fit_transform(input)  # TFIDF representation

Now, I want to manually add one feature representation2 for every letter. This feature should tell the amount of different words compared to all words in a specific letter/string:

count_vectorizer = CountVectorizer()
sum_words = np.sum(count_vectorizer.fit_transform(input).toarray(), axis=-1)
sum_different_words = np.count_nonzero(count_vectorizer.fit_transform(input).toarray(), axis=-1)
representation2 = np.divide(sum_different_words, sum_words)  # percentage of different words

The array representation2 is now an array of shape (39077,) (as expected). I now want to combine representation1 and representation2 into one feature vector representation.

I read about using FeatureUnion to combine two kinds of features in SKLearn, but I am not sure how to correctly use the Numpy array representation2as a feature here. I tried:

union = sklearn.pipeline.make_union([representation1, representation2])

But now I can't use e.g. union.get_feature_names_out(), since it throws: AttributeError: Transformer list (type list) does not provide get_feature_names_out.

What did I understand incorrectly here?


问:
Formik & MUI why doesn't it show the error text?
```<code>const availableSelection = ["foo", "bar", "john"];
</code>```
```<code>validationSchema: Yup.object({
      freelancers: Yup.array().of(Yup.string()).min(1, 'Error text')
    }),
</code>```
```<code><FormControl sx={{ width: 1 }}>
              <InputLabel>{t('Freelancers')}</InputLabel>
              <Select
                error={Boolean(formik.touched.freelancers && formik.errors.freelancers)}
                name="freelancers"
                helperText={formik.touched.freelancers && formik.errors.freelancers}
                multiple
                value={formik.values.freelancers}
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
                input={<OutlinedInput name="freelancers" label={'Freelancers'} />}
                renderValue={(selected) => (
                  <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
                    {selected.map((value) => (
                      <Chip key={value} label={value} />
                    ))}
                  </Box>
                )}
                MenuProps={MenuProps}
              >
                {availableSelection.map((name) => (
                  <MenuItem
                    key={name}
                    value={name}
                    style={getStyles(name, formik.values.freelancers, theme)}
                  >
                    {name}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
</code>```

image
image

Hello guys, have problem with multiple select. Does not show error if submitting form,but borders change color to red. Thanks for help!

Body:
const availableSelection = ["foo", "bar", "john"];

validationSchema: Yup.object({
      freelancers: Yup.array().of(Yup.string()).min(1, 'Error text')
    }),

<FormControl sx={{ width: 1 }}>
              <InputLabel>{t('Freelancers')}</InputLabel>
              <Select
                error={Boolean(formik.touched.freelancers && formik.errors.freelancers)}
                name="freelancers"
                helperText={formik.touched.freelancers && formik.errors.freelancers}
                multiple
                value={formik.values.freelancers}
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
                input={<OutlinedInput name="freelancers" label={'Freelancers'} />}
                renderValue={(selected) => (
                  <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
                    {selected.map((value) => (
                      <Chip key={value} label={value} />
                    ))}
                  </Box>
                )}
                MenuProps={MenuProps}
              >
                {availableSelection.map((name) => (
                  <MenuItem
                    key={name}
                    value={name}
                    style={getStyles(name, formik.values.freelancers, theme)}
                  >
                    {name}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>

image
image

Hello guys, have problem with multiple select. Does not show error if submitting form,but borders change color to red. Thanks for help!


问:
Drawdown calculator - decimal place bug
I have looked at a lot of other posts on drawdowns and not found a solution for this.

I have a drawdown calculator below that appears to work, but is apparently not accurate.
It returns the drawdowns for a array of returns.

I wanted the 2nd highest drawdown for this list (to 4 decimal places).

However, apparently my number is inaccurante.

I get -0.0300
and the correct answer is -0.0298

and I can't figure out what is wrong.

the code:

```<code>import numpy as np

def all_drawdowns(rets):
    dd_results = []

    cum_rets = rets.cumsum()
    i = np.argmax(np.maximum.accumulate(cum_rets) - cum_rets) # end of the period
    if i == 0:
        return dd_results
    j = np.argmax(rets[:i]) # start of period
    max_dd = cum_rets[i] - cum_rets[j]
    dd_results.append(max_dd)
    l_rets = rets[:j]
    r_rets = rets[i+1:]

    if len(l_rets) > 1:
        dd_results.extend(all_drawdowns(l_rets))

    if len(r_rets) > 1:
        dd_results.extend(all_drawdowns(r_rets))

    return sorted(dd_results)

rets_task = np.array([0.01, 0.02, 0.03, -0.01, -0.02, 0.04, 0.05, -0.02, -0.02, 0.03])

all_drawdowns(rets_task)
</code>```

The second element of the returned array should  be -0.30 as I mentioned, but should be -0.0298 (but it's not clear why.

Has anyone got any ideas?

Thank you!

Title: Drawdown calculator - decimal place bug

Body:
I have looked at a lot of other posts on drawdowns and not found a solution for this.

I have a drawdown calculator below that appears to work, but is apparently not accurate.
It returns the drawdowns for a array of returns.

I wanted the 2nd highest drawdown for this list (to 4 decimal places).

However, apparently my number is inaccurante.

I get -0.0300
and the correct answer is -0.0298

and I can't figure out what is wrong.

the code:

import numpy as np

def all_drawdowns(rets):
    dd_results = []

    cum_rets = rets.cumsum()
    i = np.argmax(np.maximum.accumulate(cum_rets) - cum_rets) # end of the period
    if i == 0:
        return dd_results
    j = np.argmax(rets[:i]) # start of period
    max_dd = cum_rets[i] - cum_rets[j]
    dd_results.append(max_dd)
    l_rets = rets[:j]
    r_rets = rets[i+1:]

    if len(l_rets) > 1:
        dd_results.extend(all_drawdowns(l_rets))

    if len(r_rets) > 1:
        dd_results.extend(all_drawdowns(r_rets))

    return sorted(dd_results)

rets_task = np.array([0.01, 0.02, 0.03, -0.01, -0.02, 0.04, 0.05, -0.02, -0.02, 0.03])

all_drawdowns(rets_task)

The second element of the returned array should  be -0.30 as I mentioned, but should be -0.0298 (but it's not clear why.

Has anyone got any ideas?

Thank you!


问:
Am I using correctly scalene profiler for python code?
I'm trying to use Scalene to profile some python code.
When I run:

```<code>scalene --reduced-profile --html --outfile ./profiling/profile_name_file.html ./profiling/profiling_script.py
</code>```

I get two error messages:

[1205/174847.087563:ERROR:elf_dynamic_array_reader.h(64)] tag not
found [1205/174847.110144:ERROR:directory_reader_posix.cc(42)] opendir
/home/user/.config/google-chrome/Crash
Reports/attachments/82a5951a-f981-4d23-badc-a9487b65f7c0: No such file
or directory (2)

Afterwards, I go to the directory from which I ran the bash command, and I find a profile.html, instead of a profile_name_file.html inside the profiling folder.

When I open that html file, the graphs look very odd.

Body:
I'm trying to use Scalene to profile some python code.
When I run:

scalene --reduced-profile --html --outfile ./profiling/profile_name_file.html ./profiling/profiling_script.py

I get two error messages:

[1205/174847.087563:ERROR:elf_dynamic_array_reader.h(64)] tag not
found [1205/174847.110144:ERROR:directory_reader_posix.cc(42)] opendir
/home/user/.config/google-chrome/Crash
Reports/attachments/82a5951a-f981-4d23-badc-a9487b65f7c0: No such file
or directory (2)

Afterwards, I go to the directory from which I ran the bash command, and I find a profile.html, instead of a profile_name_file.html inside the profiling folder.

When I open that html file, the graphs look very odd.


问:
Custom output model on Restier
I have a Restier controller that correctly returns my database content. My question is if there's a way to customize the returned model from the API.

The reason for this is that I'd like to customize the JSON returned to be directly used by a javascript application.

Title: Custom output model on Restier


问:
Mock Chrome Storage API to test extension popup
I am building a chrome extension. For this I use the Chrome Storage API in a script that runs when the popup is opened (popup.js):

chrome.storage.sync.get(...);
```
<p>However, it's much easier to develop and test the popup if I open it directly in the browser as its own web page instead of just testing it as an actual popup, since I then also have <em>Inspect element</em> and similar tools.
The only problem is that the Storage API is meant for extensions and any uses of it in my code will directly result in an error when I open the popup as a web page. So I thought it would be useful to just mock the API calls. Then I could simulate storage data as well. To do this, so far I'm using something like the following at the top of <code>popup.js</code>:</p>
<pre class="lang-js prettyprint-override"><code>let chrome = {
    storage: {
        sync: {
            get: function (a, b) {console.log("[Mock] get-Function"); },
        }
    },
}
</code>```

(Of course, to really simulate storage data this would need more than an empty function)

The problem is, however, that I only want to use the mocking for testing the popup, of course, and not for testing the addon or in production. For production I already have my own build process with webpack, which bundles the whole thing for me.
Is it possible that I create a similar build process (possibly also with webpack) that I can then run from the command line and that actively includes mocking in the code, for example by adding it as a dependency.
Or what is basically the best approach if you want to use a piece of code for some special test processes and never otherwise?

So far, I've tried creating my own file that overrides the Chrome API with empty functions and exports that. popup.js should then check if this file exists and if so import the overridden functions. This would work in itself, if webpack didn't also always bundle the mock file with the production build. It was not possible for me to get webpack to ignore dependencies completely by any settings.

Body:
I am building a chrome extension. For this I use the Chrome Storage API in a script that runs when the popup is opened (popup.js):

chrome.storage.sync.get(...);

However, it's much easier to develop and test the popup if I open it directly in the browser as its own web page instead of just testing it as an actual popup, since I then also have Inspect element and similar tools.
The only problem is that the Storage API is meant for extensions and any uses of it in my code will directly result in an error when I open the popup as a web page. So I thought it would be useful to just mock the API calls. Then I could simulate storage data as well. To do this, so far I'm using something like the following at the top of popup.js:

let chrome = {
    storage: {
        sync: {
            get: function (a, b) {console.log("[Mock] get-Function"); },
        }
    },
}

(Of course, to really simulate storage data this would need more than an empty function)

The problem is, however, that I only want to use the mocking for testing the popup, of course, and not for testing the addon or in production. For production I already have my own build process with webpack, which bundles the whole thing for me.
Is it possible that I create a similar build process (possibly also with webpack) that I can then run from the command line and that actively includes mocking in the code, for example by adding it as a dependency.
Or what is basically the best approach if you want to use a piece of code for some special test processes and never otherwise?

So far, I've tried creating my own file that overrides the Chrome API with empty functions and exports that. popup.js should then check if this file exists and if so import the overridden functions. This would work in itself, if webpack didn't also always bundle the mock file with the production build. It was not possible for me to get webpack to ignore dependencies completely by any settings.


问:
Coerce values with as_hms in R
In R, is there a way to coerce a value (NA for example) instead of throwing errors when converting string to hms in as_hms?

I don't see coerce argument in the document and I'm scratching my head on this.

```<code>library(hms)
as_hms(c('11:15:00',"12:00","3"))
</code>```

Error in abort_lossy_cast():
! Lossy cast from  to  at position(s) 2, 3
Run rlang::last_error() to see where the error occurred.

Title: Coerce values with as_hms in R

Body:
In R, is there a way to coerce a value (NA for example) instead of throwing errors when converting string to hms in as_hms?

I don't see coerce argument in the document and I'm scratching my head on this.

library(hms)
as_hms(c('11:15:00',"12:00","3"))

Error in abort_lossy_cast():
! Lossy cast from  to  at position(s) 2, 3
Run rlang::last_error() to see where the error occurred.


问:
Android Insert Intent Calendar Event Not Trigger startActivityForResult or ActivityResultLauncher
I want to add a calendar event with intent. The code below does this successfully.

```<code>val startMillis: Long = Calendar.getInstance().run {
    set(2012, 0, 19, 7, 30)
    timeInMillis
}
val endMillis: Long = Calendar.getInstance().run {
    set(2012, 0, 19, 8, 30)
    timeInMillis
}
val intent = Intent(Intent.ACTION_INSERT)
        .setData(CalendarContract.Events.CONTENT_URI)
        .putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, startMillis)
        .putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endMillis)
        .putExtra(CalendarContract.Events.TITLE, "Yoga")
        .putExtra(CalendarContract.Events.DESCRIPTION, "Group class")
        .putExtra(CalendarContract.Events.EVENT_LOCATION, "The gym")
        .putExtra(CalendarContract.Events.AVAILABILITY, CalendarContract.Events.AVAILABILITY_BUSY)
        .putExtra(Intent.EXTRA_EMAIL, "rowan@example.com,trevor@example.com")
startActivity(intent)
</code>```

But I need the id of the calendar event added afterwards.
I used a registerContentObserver for this. So registerContentObserver is triggered when an event is registered. Then I consider the last added calendar event as the event I added with intent. But registerContentObserver takes a long time like 4 seconds to trigger.

I can't catch this with startActivityForResult or new method ActivityResultLauncher. Is there a method to this?

Body:
I want to add a calendar event with intent. The code below does this successfully.

val startMillis: Long = Calendar.getInstance().run {
    set(2012, 0, 19, 7, 30)
    timeInMillis
}
val endMillis: Long = Calendar.getInstance().run {
    set(2012, 0, 19, 8, 30)
    timeInMillis
}
val intent = Intent(Intent.ACTION_INSERT)
        .setData(CalendarContract.Events.CONTENT_URI)
        .putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, startMillis)
        .putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endMillis)
        .putExtra(CalendarContract.Events.TITLE, "Yoga")
        .putExtra(CalendarContract.Events.DESCRIPTION, "Group class")
        .putExtra(CalendarContract.Events.EVENT_LOCATION, "The gym")
        .putExtra(CalendarContract.Events.AVAILABILITY, CalendarContract.Events.AVAILABILITY_BUSY)
        .putExtra(Intent.EXTRA_EMAIL, "rowan@example.com,trevor@example.com")
startActivity(intent)

But I need the id of the calendar event added afterwards.
I used a registerContentObserver for this. So registerContentObserver is triggered when an event is registered. Then I consider the last added calendar event as the event I added with intent. But registerContentObserver takes a long time like 4 seconds to trigger.

I can't catch this with startActivityForResult or new method ActivityResultLauncher. Is there a method to this?


问:
Why am I getting an error calling for an object reference in C# API Call
I have an app that has a lot of C# API calls and I have one call that is saying "An object reference is required for the non-static field, method, or property". The code that is giving that error looks like this:

```<code>    [HttpGet("api/foo/bar/data/{dataId}")]
    public List<Model> GetDataSource(string dataId)
    {
      return ModelBuilder.GetDataSource(dataId);
    }
</code>```

I have other API's in this file that are the exact same structure but they are fine. The only difference is that the others are calling a different builder file. I have included the references to the new builder file in my using statements and the opening statements of the class.

One of the other API's that is working is:

```<code>    [HttpGet("api/foo/bar/model/{modelid}")]
    public List<Model> GetModel(string modelid)
    {
      return mBuilder.GetModel(modelid);
    }
</code>```

Further, if I change the builder file that it's going to it resolves the error. The definition of the method in the builder file is the exact same regardless of which file I put it in as I just copied what I had written and pasted it into the other file.

** Edit to show what the Builder files look like***

So my Builder files are both defined with public class and from my perspective seem like they are identical files.

The ModelBuilder looks like:

```<code>//using statements
  namespace Business
  {
    public class ModelBuilder
    {
      public List<Model> GetDataSource(string dataId)
    {
      var object = this.entityCollection.Find(item => item.id == dataId).ToList();
      var entityIDs = new HashSet<string>();

      foreach (var object in objects)
      {
        entityIDs.Add(object.id);
      }

      if (object == null)
      {
        return new List<Model>();
      }

      var filter = Builders<AllowedObjects>.Filter.In("id", entityIDs);
      var items = allowedObjectsCollection.Find(filter).ToList();
      var objects = new List<Model>();

      foreach (var mObj in items)
      {
        var obj = tmBuilder.ConvertFromAllowedObjectToModel(mObj);
        obj.Add(obj);
      }

      return obj;
    }
    }
  }
</code>```

My mBuilder file looks like:

```<code>//using statements
  namespace Utilities
  {
    public class mBuilder
    {
      public List<Model> GetDataSource(string dataId)
    {
      var object = this.entityCollection.Find(item => item.id == dataId).ToList();
      var entityIDs = new HashSet<string>();

      foreach (var object in objects)
      {
        entityIDs.Add(object.id);
      }

      if (object == null)
      {
        return new List<Model>();
      }

      var filter = Builders<AllowedObjects>.Filter.In("id", entityIDs);
      var items = allowedObjectsCollection.Find(filter).ToList();
      var objects = new List<Model>();

      foreach (var mObj in items)
      {
        var obj = tmBuilder.ConvertFromAllowedObjectToModel(mObj);
        obj.Add(obj);
      }

      return obj;
    }
    }
</code>```

So I'm confused at why I get the object reference error when I try to send the API to the ModelBuilder but not when I send it to the mBuilder.

Body:
I have an app that has a lot of C# API calls and I have one call that is saying "An object reference is required for the non-static field, method, or property". The code that is giving that error looks like this:

    [HttpGet("api/foo/bar/data/{dataId}")]
    public List<Model> GetDataSource(string dataId)
    {
      return ModelBuilder.GetDataSource(dataId);
    }

I have other API's in this file that are the exact same structure but they are fine. The only difference is that the others are calling a different builder file. I have included the references to the new builder file in my using statements and the opening statements of the class.

One of the other API's that is working is:

    [HttpGet("api/foo/bar/model/{modelid}")]
    public List<Model> GetModel(string modelid)
    {
      return mBuilder.GetModel(modelid);
    }

Further, if I change the builder file that it's going to it resolves the error. The definition of the method in the builder file is the exact same regardless of which file I put it in as I just copied what I had written and pasted it into the other file.

** Edit to show what the Builder files look like***

So my Builder files are both defined with public class and from my perspective seem like they are identical files.

The ModelBuilder looks like:

//using statements
  namespace Business
  {
    public class ModelBuilder
    {
      public List<Model> GetDataSource(string dataId)
    {
      var object = this.entityCollection.Find(item => item.id == dataId).ToList();
      var entityIDs = new HashSet<string>();

      foreach (var object in objects)
      {
        entityIDs.Add(object.id);
      }

      if (object == null)
      {
        return new List<Model>();
      }

      var filter = Builders<AllowedObjects>.Filter.In("id", entityIDs);
      var items = allowedObjectsCollection.Find(filter).ToList();
      var objects = new List<Model>();

      foreach (var mObj in items)
      {
        var obj = tmBuilder.ConvertFromAllowedObjectToModel(mObj);
        obj.Add(obj);
      }

      return obj;
    }
    }
  }

My mBuilder file looks like:

//using statements
  namespace Utilities
  {
    public class mBuilder
    {
      public List<Model> GetDataSource(string dataId)
    {
      var object = this.entityCollection.Find(item => item.id == dataId).ToList();
      var entityIDs = new HashSet<string>();

      foreach (var object in objects)
      {
        entityIDs.Add(object.id);
      }

      if (object == null)
      {
        return new List<Model>();
      }

      var filter = Builders<AllowedObjects>.Filter.In("id", entityIDs);
      var items = allowedObjectsCollection.Find(filter).ToList();
      var objects = new List<Model>();

      foreach (var mObj in items)
      {
        var obj = tmBuilder.ConvertFromAllowedObjectToModel(mObj);
        obj.Add(obj);
      }

      return obj;
    }
    }

So I'm confused at why I get the object reference error when I try to send the API to the ModelBuilder but not when I send it to the mBuilder.


问:
Is a tearDown function in a below class really necessary?
That`s a code from one of the DRF tutorial. What is the point of tearDown fn if there is nothing new added?</p>
```<code>from rest_framework.test import APITestCase
from django.urls import reverse

class TestSetUp(APITestCase):

    def setUp(self):
        self.register_url = reverse('register')
        self.user_data = {
            'email': 'example@test.com',
            ...
        }
        return super().setUp()

    def tearDown(self):
        return super().tearDown()
</code>```

Body:
That`s a code from one of the DRF tutorial. What is the point of tearDown fn if there is nothing new added?

from rest_framework.test import APITestCase
from django.urls import reverse

class TestSetUp(APITestCase):

    def setUp(self):
        self.register_url = reverse('register')
        self.user_data = {
            'email': 'example@test.com',
            ...
        }
        return super().setUp()

    def tearDown(self):
        return super().tearDown()


问:
Using IntelliJ for Swing GUI
this is my first post on stack overflow. I just started out trying to learn how to code (big big noob) and stumbled across a problem that seems impossible to fix for me:

My Uni uses Eclipse for Java programming. I started with IntelliJ which I very much prefer by now and I would like to keep using it. In todays lecture, our professor introduced us to Swing GUI. In Eclipse, she uses Window Builder which is not available for IntelliJ. I thought this would for sure not be a problem until she created a new GUI Class (uploaded a pic with all the options available in Eclipse to create a new GUI). She created a "Application Window" and instantly has some lines of code that are able to run an empty Panel which she uses as a basis to add more content (added the code that comes with creating a new "Application Window" in Eclipse). This option is not available in IntelliJ.

Please forgive me my bad English and super beginner, non existing knowledge of Java.

I've tried to get around this for the whole evening and can't seem to find a working solution.

Basically if someone knows how I can get a working GUI window in IntelliJ that I can use as a basis - that would already help a lot.

How creating a new Swing Project looks in Eclipse

```<code>public class guiVorlage {

    private JFrame frame;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    guiVorlage window = new guiVorlage();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public guiVorlage() {
        initialize();
    }

    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

}

</code>```

I really don't want to switch to Eclipse.

Tried:

Copying + Adjusting the code from Eclipse in an IntelliJ GUI

Watched tutorials but the ones that I watched did not achieve the exact same thing as in the lecture

Write the code manually

I need to be able to have a running GUI in IntelliJ that is empty an can be used as a basis to add more content.

Title: Using IntelliJ for Swing GUI

Body:
this is my first post on stack overflow. I just started out trying to learn how to code (big big noob) and stumbled across a problem that seems impossible to fix for me:

My Uni uses Eclipse for Java programming. I started with IntelliJ which I very much prefer by now and I would like to keep using it. In todays lecture, our professor introduced us to Swing GUI. In Eclipse, she uses Window Builder which is not available for IntelliJ. I thought this would for sure not be a problem until she created a new GUI Class (uploaded a pic with all the options available in Eclipse to create a new GUI). She created a "Application Window" and instantly has some lines of code that are able to run an empty Panel which she uses as a basis to add more content (added the code that comes with creating a new "Application Window" in Eclipse). This option is not available in IntelliJ.

Please forgive me my bad English and super beginner, non existing knowledge of Java.

I've tried to get around this for the whole evening and can't seem to find a working solution.

Basically if someone knows how I can get a working GUI window in IntelliJ that I can use as a basis - that would already help a lot.

How creating a new Swing Project looks in Eclipse

public class guiVorlage {

    private JFrame frame;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    guiVorlage window = new guiVorlage();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public guiVorlage() {
        initialize();
    }

    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

}

I really don't want to switch to Eclipse.

Tried:

Copying + Adjusting the code from Eclipse in an IntelliJ GUI

Watched tutorials but the ones that I watched did not achieve the exact same thing as in the lecture

Write the code manually

I need to be able to have a running GUI in IntelliJ that is empty an can be used as a basis to add more content.


问:
Comparing 2D np arrays with ssim: ValueError: win_size exceeds image extent. If the input is a multichannel (color) image, set multichannel=True
I am trying to calculate SSIM for 2 numpy arrays using structural_similarity from skimage.metrics:

ydata.shape = (3, 230)
ydata3.shape = (3, 230)
```
<p><em>When I try to calculate SSIM:</em></p>
<pre class="lang-py prettyprint-override"><code>mse_value = mean_squared_error(ydata, ydata3)
ssim_value = ssim(ydata, ydata3, data_range=ydata3.max() - ydata.min())**
</code>```

I have the error:

"win_size exceeds image extent.  If the input is a multichannel "
ValueError: win_size exceeds image extent.  If the input is a multichannel (color) image, set multichannel=True.**
```
<p><em>I tried to set <code>multichannel = True</code> but it does not work.</em></p>
<pre class="lang-py prettyprint-override"><code>ssm: ssim_value = ssim(ydata, ydata3, multichannel= True, data_range=ydata3.max() - ydata.min())
</code>```

I also tried to increase the dimension of the array with:

ydata = ydata.reshape(ydata.shape[0], ydata.shape[1], 1)
```

The new shape of the arrays is ((3, 230, 1), (3, 230, 1)).
However it keeps showing the same error

I tried also flatten but it changes a lot my results.

Any suggestions or help?

Body:
I am trying to calculate SSIM for 2 numpy arrays using structural_similarity from skimage.metrics:

ydata.shape = (3, 230)
ydata3.shape = (3, 230)

When I try to calculate SSIM:

mse_value = mean_squared_error(ydata, ydata3)
ssim_value = ssim(ydata, ydata3, data_range=ydata3.max() - ydata.min())**

I have the error:

"win_size exceeds image extent.  If the input is a multichannel "
ValueError: win_size exceeds image extent.  If the input is a multichannel (color) image, set multichannel=True.**

I tried to set multichannel = True but it does not work.

ssm: ssim_value = ssim(ydata, ydata3, multichannel= True, data_range=ydata3.max() - ydata.min())

I also tried to increase the dimension of the array with:

ydata = ydata.reshape(ydata.shape[0], ydata.shape[1], 1)

The new shape of the arrays is ((3, 230, 1), (3, 230, 1)).
However it keeps showing the same error

I tried also flatten but it changes a lot my results.

Any suggestions or help?


问:
SQL DDL generate patch sql
I am currently using Apache DdlUtils to generate SQL for different databases using XML.
Is there a tool that can automatically generate patch SQL for different versions?

For example, from version 1.0 to 2.0:

Some tables added new columns.

Some tables modified column types.

Added new insert statements.

I think my current Apache DdlUtils should not be able to do this.

I expect to output ALTER TABLE COLUMN SQL statements and new insert statements for this time.
I expect that I can specify the database definition contents of two versions and produce patch SQL based on the differences.

Title: SQL DDL generate patch sql


问:
react react-router-dom not found page error with live url
react-router-dom v6.4.3

npm v9.1.1

node v18.12.1

I am currently working on a react project.

I set the path using react-router-dom, it worked local environment.

But, when I upload to the server build file, I get a 404 error.

Below is my code

```<code>import { BrowserRouter, Routes, Route } from 'react-router-dom';
import Home from './pages/index/Home';
import Aboutus from './pages/sitemap/Aboutus';
import Privacypolicy from './pages/sitemap/Privacypolicy';
import Terms from './pages/sitemap/Terms';
import Contactus from './pages/sitemap/Contactus';
import Advertising from './pages/sitemap/Advertising';
import NotFound from './pages/404/NotFound';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <BrowserRouter>
      <NavBarElements />
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/Company/AboutUs" element={<Aboutus />} errorElement={<NotFound />} />
        <Route path="/Company/TermsOfService" element={<Terms />} errorElement={<NotFound />} />
        <Route path="/Company/PrivacyPolicy" element={<Privacypolicy />} errorElement={<NotFound />} />
        <Route path="/Company/Advertising" element={<Advertising />} errorElement={<NotFound />} />
        <Route path="/Company/ContactUs" element={<Contactus />} errorElement={<NotFound />} />

      </Routes>
      <Footer />
    </BrowserRouter>

  </React.StrictMode>
);

</code>```
```<code><span className='footer-sitemap'>
  <a href='/Company/AboutUs' className='text-reset'>
   About Us
  </a>
</span>
<span className='footer-sitemap'>
  <a href='/Company/TermsOfService' className='text-reset'>
   Terms of Service
  </a>
</span>
<span className='footer-sitemap'>
  <a href='/Company/PrivacyPolicy' className='text-reset'>
   Privacy Policy
  </a>
</span>
<span className='footer-sitemap'>
  <a href='/Company/Advertising' className='text-reset'>
   Advertising
  </a>
</span>
<span className='footer-sitemap'>
  <a href='/Company/ContactUs' className='text-reset'>
   Contact Us
  </a>
</span>
</code>```

code

index page

when i click about us

I don't understand...
I also added errorElement. It also not working...

Any solution for this?

I tried using  but it's showing same issue

Body:
react-router-dom v6.4.3

npm v9.1.1

node v18.12.1

I am currently working on a react project.

I set the path using react-router-dom, it worked local environment.

But, when I upload to the server build file, I get a 404 error.

Below is my code

import { BrowserRouter, Routes, Route } from 'react-router-dom';
import Home from './pages/index/Home';
import Aboutus from './pages/sitemap/Aboutus';
import Privacypolicy from './pages/sitemap/Privacypolicy';
import Terms from './pages/sitemap/Terms';
import Contactus from './pages/sitemap/Contactus';
import Advertising from './pages/sitemap/Advertising';
import NotFound from './pages/404/NotFound';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <BrowserRouter>
      <NavBarElements />
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/Company/AboutUs" element={<Aboutus />} errorElement={<NotFound />} />
        <Route path="/Company/TermsOfService" element={<Terms />} errorElement={<NotFound />} />
        <Route path="/Company/PrivacyPolicy" element={<Privacypolicy />} errorElement={<NotFound />} />
        <Route path="/Company/Advertising" element={<Advertising />} errorElement={<NotFound />} />
        <Route path="/Company/ContactUs" element={<Contactus />} errorElement={<NotFound />} />

      </Routes>

    </BrowserRouter>

  </React.StrictMode>
);

   About Us

   Terms of Service

   Privacy Policy

   Advertising

   Contact Us

code

index page

when i click about us

I don't understand...
I also added errorElement. It also not working...

Any solution for this?

I tried using  but it's showing same issue


问:
Does TDengine support Chinese character as column and tag name?
I want to create a super table for my business requirement in TDengine. We need to represent some column and tag names with Chinese character. I didn't find examples for it.

Does anyone know that can we implement it?


问:
SpriteKit. How to play a sound when a sprite moves, but not when it stays still
I need to associate sound with the movement of a sprite. Movement can be as a result of physics, not as a result of an SKAction. When the object is sliding thee should be sliding sound throughout the time when it is sliding, and then a different sound when it bumps into a rock and goes up in the air. When the object is airborne, there is no sound, till it falls again - a falling sound, and then slides down with a sliding sound.   The sounds associated with the collision ( rock, ground and so on ) are straightforward and work fine.  But am having difficulty associating the sound with movement.

The closest result I have is to check  the velocity of the sprite's physics body every update cycle and play or stop the sound based on whether the velocity is greater than zero.  I tried SKAction.playSoundFileNamed first - the sound kept going even when the object was not moving. I tried adding an SKAudioNode with Play and Stop, with no better result.  I finally tried using AVAudioPlayer to play and Pause , which yielded the best results, but the sliding sound still played past the sliding action.

What is the best way to do this?

My code for playing the sound is as follows:

```<code>      var blockSliding = false
      for block in gameBlocks {
         if (block.physicsBody?.velocity.dx ?? 0) + (ball.physicsBody?.velocity.dy  ?? 0) > 0.05 {
            blockSliding = true
            break
         }
      }
      if slideSound.isPlaying {
         if !blockSliding {
            slideSound.pause()
         }
      } else {
         if blockSliding {
            slideSound.play()
         }
      }
</code>```

I have setup slideSound earlier loading the appropriate sound file into an AVAudioPlayer

Body:
I need to associate sound with the movement of a sprite. Movement can be as a result of physics, not as a result of an SKAction. When the object is sliding thee should be sliding sound throughout the time when it is sliding, and then a different sound when it bumps into a rock and goes up in the air. When the object is airborne, there is no sound, till it falls again - a falling sound, and then slides down with a sliding sound.   The sounds associated with the collision ( rock, ground and so on ) are straightforward and work fine.  But am having difficulty associating the sound with movement.

The closest result I have is to check  the velocity of the sprite's physics body every update cycle and play or stop the sound based on whether the velocity is greater than zero.  I tried SKAction.playSoundFileNamed first - the sound kept going even when the object was not moving. I tried adding an SKAudioNode with Play and Stop, with no better result.  I finally tried using AVAudioPlayer to play and Pause , which yielded the best results, but the sliding sound still played past the sliding action.

What is the best way to do this?

My code for playing the sound is as follows:

      var blockSliding = false
      for block in gameBlocks {
         if (block.physicsBody?.velocity.dx ?? 0) + (ball.physicsBody?.velocity.dy  ?? 0) > 0.05 {
            blockSliding = true
            break
         }
      }
      if slideSound.isPlaying {
         if !blockSliding {
            slideSound.pause()
         }
      } else {
         if blockSliding {
            slideSound.play()
         }
      }

I have setup slideSound earlier loading the appropriate sound file into an AVAudioPlayer


问:
How can I solve this problem as when I install tensorflow package in any version it throw this error for me?
Error
and I use this command to install this package in jupyter notebook
import sys !{sys.executable} -m pip install tensorflow==1.14
Anyone can help me to solve this problem ?
I searched a lot about this problem and there's no an accurate solution about it

I try to delete wrapt manually , it throws to me the same error .


问:
How to write custom log4j2 asynclogger?
Need to send application logs to azure eventhub in async way using log4j2 asynclogger

I tried with log4j async appender. But from online research it's recommended to use log4j2 asynclogger. Can anyone help in providing sample application with custom log4j2 asynclogger.

Title: How to write custom log4j2 asynclogger?


问:
i can't use the symboles "<" and ">" in my physical keybord
I am using a Lenovo laptop; it has an AZERTY keyboard, but I can't use the symbols "<" and ">" unless I switch it to a QWERTY, and that will change all of my buttons, and I need those symbols in Android Studio (I don't know if that will help, and I am new to Android Studio), any ideas? Thanks

I did search how to customize a button click or something like that but i was not lucky


问:
recursive count based on category
I have a two table

Table1:

ID
A1

AAA
a

BBB
b

CCC
a

DDD
a

EEE
b

Table 2:

ID1
ID2

AAA
BBB

AAA
CCC

CCC
EEE

CCC
DDD

Here, ID1 and ID2 both point to ID of table 1.
What I want is for ID1 in table two I want a tuple that counts a number of the corresponding values in ID2 for each attribute A1.
For eg

Output:

ID1
A1
Count

AAA
a
2

AAA
b
2

CCC
a
1

CCC
b
1

explanation:

```<code>AAA -> (BBB, b)
AAA -> (CCC, a)
AAA -> CCC -> (EEE, b)
AAA -> CCC -> (DDD, a)
</code>```

Therefore, (AAA, a, 2) and (AAA,b, 2)

```<code>CCC -> (EEE, b)
CCC -> (DDD, a)
</code>```

Therefore, (CCC, a, 1) and (CCC, b, 1)

The rest do not have any corresponding ID2 attribute in table 2.

I know this will possibly require recursive queries but can't seem to understand how to achieve this.

Title: recursive count based on category

Body:
I have a two table

Table1:

ID
A1

AAA
a

BBB
b

CCC
a

DDD
a

EEE
b

Table 2:

ID1
ID2

AAA
BBB

AAA
CCC

CCC
EEE

CCC
DDD

Here, ID1 and ID2 both point to ID of table 1.
What I want is for ID1 in table two I want a tuple that counts a number of the corresponding values in ID2 for each attribute A1.
For eg

Output:

ID1
A1
Count

AAA
a
2

AAA
b
2

CCC
a
1

CCC
b
1

explanation:

AAA -> (BBB, b)
AAA -> (CCC, a)
AAA -> CCC -> (EEE, b)
AAA -> CCC -> (DDD, a)

Therefore, (AAA, a, 2) and (AAA,b, 2)

CCC -> (EEE, b)
CCC -> (DDD, a)

Therefore, (CCC, a, 1) and (CCC, b, 1)

The rest do not have any corresponding ID2 attribute in table 2.

I know this will possibly require recursive queries but can't seem to understand how to achieve this.


问:
Cloud build error: failed to build: executing lifecycle. This may be the result of using an untrusted builder: failed with status code: 51
I am trying to deploy a template Django project to cloud run using cloud shell from the following tutorial: https://codelabs.developers.google.com/codelabs/cloud-run-django
In step 7, on running the command:

```<code>gcloud builds submit --pack image=gcr.io/${PROJECT_ID}/myimage
</code>```

to build the application image, this error is coming:

`ERROR: failed to build: exit status 1 ERROR: failed to build:
executing lifecycle. This may be the result of using an untrusted
builder: failed with status code: 51 ERROR ERROR: build step 0
"gcr.io/k8s-skaffold/pack" failed: step exited with non-zero status: 1

BUILD FAILURE: Build step failure: build step 0
"gcr.io/k8s-skaffold/pack" failed: step exited with non-zero status: 1
ERROR: (gcloud.builds.submit) build
75a52dae-9a4f-4591-af13-5fe1228533b4 completed with status "FAILURE"`

The file migration.yaml is same as the tutorial and I have followed all steps exactly as they were in the tutorial.
Can someone please help me with this error ?

Body:
I am trying to deploy a template Django project to cloud run using cloud shell from the following tutorial: https://codelabs.developers.google.com/codelabs/cloud-run-django
In step 7, on running the command:

gcloud builds submit --pack image=gcr.io/${PROJECT_ID}/myimage

to build the application image, this error is coming:

`ERROR: failed to build: exit status 1 ERROR: failed to build:
executing lifecycle. This may be the result of using an untrusted
builder: failed with status code: 51 ERROR ERROR: build step 0
"gcr.io/k8s-skaffold/pack" failed: step exited with non-zero status: 1

BUILD FAILURE: Build step failure: build step 0
"gcr.io/k8s-skaffold/pack" failed: step exited with non-zero status: 1
ERROR: (gcloud.builds.submit) build
75a52dae-9a4f-4591-af13-5fe1228533b4 completed with status "FAILURE"`

The file migration.yaml is same as the tutorial and I have followed all steps exactly as they were in the tutorial.
Can someone please help me with this error ?


问:
SyntaxError: Unexpected token o in JSON at position 1 on AWS server
I'm currently creating REST APIs using NodeJs.
On my localhost machine where my node version is v16.15.1, I can parse the JSON data using JSON.parse. Here's what the output looks like:

```<code>"fields": [
        {
        "type": "Radio",
        "dataType": "Boolean",
        "fieldName": "Is covered",
        "isRequired": "Y"
    },
    {
            "type": "Textbox",
            "dataType": "String",
        "fieldName": "Length",
        "isRequired": "Y"
    },
    {
         "type": "Textbox",
         "dataType": "String",
         "fieldName": "Width",
         "isRequired": "Y"
    },
    {
             "type": "Textbox",
         "dataType": "String",
         "fieldName": "Net size",
         "isRequired": "Y"
    }
],
</code>```

However, after I deployed the app in my Amazon server EC2 Instance with nodejs version v16.18.1, the result is different, it says SyntaxError: Unexpected token o in JSON at position 1.

I tried to search for an answers and found this json.stringify, however, it is just replicating the issue in my localhost

Body:
I'm currently creating REST APIs using NodeJs.
On my localhost machine where my node version is v16.15.1, I can parse the JSON data using JSON.parse. Here's what the output looks like:

"fields": [
        {
        "type": "Radio",
        "dataType": "Boolean",
        "fieldName": "Is covered",
        "isRequired": "Y"
    },
    {
            "type": "Textbox",
            "dataType": "String",
        "fieldName": "Length",
        "isRequired": "Y"
    },
    {
         "type": "Textbox",
         "dataType": "String",
         "fieldName": "Width",
         "isRequired": "Y"
    },
    {
             "type": "Textbox",
         "dataType": "String",
         "fieldName": "Net size",
         "isRequired": "Y"
    }
],

However, after I deployed the app in my Amazon server EC2 Instance with nodejs version v16.18.1, the result is different, it says SyntaxError: Unexpected token o in JSON at position 1.

I tried to search for an answers and found this json.stringify, however, it is just replicating the issue in my localhost


问:
MongoDB database instance to use for auth branch of MDN "Local Library" Express (Node) tutorial?
Which pre-set MongoDB connection URL supports running the version of the MDN "Local Library" Express (Node) tutorial that exists on the "auth" branch?

Using the mongodb://******:******@ds119748.mlab.com:19748/local_library connection URL in app.js on that branch throws an ENOTFOUND error[1].  Using the connection URL from the current main branch's app.js (as of 2022-12-05, mongodb+srv://******:******@cluster0.a9azn.mongodb.net/local_library) throws a different error:

Error [MongoError]: (Unauthorized) not authorized on admin to execute command { insert: "system.indexes", documents: [[{ns admin.sessions} {key [{expires 1}]} {name expires_1} {expireAfterSeconds 0} {unique false}]], ordered: true }

If neither of the above MongoDB instances can support running the "auth" code, would someone need to diverge very much from the tutorial guide at https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/mongoose#setting_up_the_mongodb_database to get one working for auth?

[1] Error [MongoError]: failed to connect to server [ds119748.mlab.com:19748] on first connect [Error: getaddrinfo ENOTFOUND ds119748.mlab.com at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:71:26)


问:
How to generate a credential for JWT authentication for a machine user (programmatic/non-human) using Google OAuth?
I have a django restframework backend and a react frontend that uses google social auth to authenticate human users.  The flow is a relatively simple JWT flow.

The user goes to my website

The user logs in with their google account

the google window sends a credential to my backend

the credential is verified on the backend

I send back an access token that allows the user to use my app which makes rest calls to my backend

I would like to generate a similar access token to pass to the backend so that I can access my api from lambda functions.

Is it possible to use the client_id and client_secret from my google console credentials to generate the same type of token to send to my backend?  I've also looked into google service accounts, but this seems to be used specifically for accessing google services, not a generic API that is simply protected via google authentication.

If none of the above options work? How would you recommend I authenticate machine users via google auth?


问:
Struggling to make a Login Authentication for js.node + mongoDB code
Currently attempting to make a register/ login page for a website.
Made a register where it saves username and password to mongoDB.
However i am stuck on the login authentication part, if someone coudld help me out that would be nice.

I attempted to add api passport but I do not have enough knowledge on it to implement a authentication. I want the login screen to verify if the inputed username and password are valid before redirecting the user to the homepage.

This is my server.js code

```<code>const express = require('express');
const app = express();
const router = express.Router();
const mongoose = require('mongoose')
const bodyParser = require('body-parser');
const passport = require("passport");
const passportLocalMongoose = require("passport-local-mongoose");
const LocalStrategy = require("passport-local");

var User = require("./models/user");

app.use(express.urlencoded({ extended: false }))
app.use(express.json());

//connect to db
mongoose.connect("mongodb+srv://group4:s0ftwar3@bankdata.tomj87l.mongodb.net/?retryWrites=true&w=majority", { useNewUrlParser: true, useUnifiedTopology: true }, connected());

function connected() {
    console.log('Connected to DB');
}

//password
app.use(require("express-session")({
    secret: "123",
    resave: false,
    saveUninitialized: false
}));

//initialize passport
app.use(passport.initialize());
app.use(passport.session());

//routes
//home page
app.get("/", function (req, res) {
    res.sendFile(__dirname + "/views/home.html")
});
//login form

app.get('/login', function (req, res) {
    res.sendFile(__dirname + "/views/login.html")
})

//

//Handling user login
app.post("/login", passport.authenticate("local", {
    successRedirect: "/secret",
    failureRedirect: "/login"
}), function (req, res) {
});

//register form
app.get("/register", function (req, res) {
    res.sendFile(__dirname + "/views/register.html");
});

app.post("/register", function (req, res) {

    const user = new User({
        username: req.body.username,
        password : req.body.password
    });

    user.save((err, user) => {
        if (err) {
            res.status(500)
                .send({
                    message: err
                });
            return res.sendFile(__dirname + "/views/register.html");;
        }
        passport.authenticate("local")(
            req, res, function () {
                res.sendFile(__dirname + "/views/homepage.html");
            });
    });
});

app.listen(1337)

</code>```

my user.js

```<code>const mongoose = require('mongoose');
const Joi = require('joi');

const userSchema = new mongoose.Schema({
    username: {
        type: String,
        unique: true,
        required: true
    },
    password: {
        type: String,
        max: 1024,
        min: 6,
        required: true
    }

});

function validateUser(user) {
    const schema = {
        username: Joi.string().min(5).max(50).required(),
        email: Joi.string().min(5).max(255).required().email(),
        password: Joi.string().min(5).max(255).required()
    };
    return Joi.validate(user, schema);
}

module.exports = mongoose.model('User', userSchema);
exports.validate = validateUser;
</code>```

and my login.html

```<code><!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type = "text/css" href="login.css" />
    <title>Global Teller Machine 2.0</title>
    <meta charset="utf-8" />
</head>
<body>
    <div id="window">
        <a href="setting.html">
            <img id="setting_icon" src="../assets/setting_icon.png" alt="Setting" />
        </a>
        <div>
            <h1 class="header">
                <b class="header">Welcome to GTM 2.0</b>
            </h1>
            <h3 class="header">Please sign in to begin</h3>
        </div>
        <form action="/login" method="post">
            <div>
                <label>Username</label>
                </br>
                <input type="text" placeholder="Enter Username" name="username" id="username" required>
            </div>
                </br>
                <div>
                    <label>Password</label>
                    </br>
                    <input type="password" placeholder="Enter Password" name="password" id="password" required>
                </div>
                </br>
                <input id="data" type="submit" value="Login" />
            </div>

        </form>
    </div>
</body>
</html>
</code>```

Body:
Currently attempting to make a register/ login page for a website.
Made a register where it saves username and password to mongoDB.
However i am stuck on the login authentication part, if someone coudld help me out that would be nice.

I attempted to add api passport but I do not have enough knowledge on it to implement a authentication. I want the login screen to verify if the inputed username and password are valid before redirecting the user to the homepage.

This is my server.js code

const express = require('express');
const app = express();
const router = express.Router();
const mongoose = require('mongoose')
const bodyParser = require('body-parser');
const passport = require("passport");
const passportLocalMongoose = require("passport-local-mongoose");
const LocalStrategy = require("passport-local");

var User = require("./models/user");

app.use(express.urlencoded({ extended: false }))
app.use(express.json());

//connect to db
mongoose.connect("mongodb+srv://group4:s0ftwar3@bankdata.tomj87l.mongodb.net/?retryWrites=true&w=majority", { useNewUrlParser: true, useUnifiedTopology: true }, connected());

function connected() {
    console.log('Connected to DB');
}

//password
app.use(require("express-session")({
    secret: "123",
    resave: false,
    saveUninitialized: false
}));

//initialize passport
app.use(passport.initialize());
app.use(passport.session());

//routes
//home page
app.get("/", function (req, res) {
    res.sendFile(__dirname + "/views/home.html")
});
//login form

app.get('/login', function (req, res) {
    res.sendFile(__dirname + "/views/login.html")
})

//

//Handling user login
app.post("/login", passport.authenticate("local", {
    successRedirect: "/secret",
    failureRedirect: "/login"
}), function (req, res) {
});

//register form
app.get("/register", function (req, res) {
    res.sendFile(__dirname + "/views/register.html");
});

app.post("/register", function (req, res) {

    const user = new User({
        username: req.body.username,
        password : req.body.password
    });

    user.save((err, user) => {
        if (err) {
            res.status(500)
                .send({
                    message: err
                });
            return res.sendFile(__dirname + "/views/register.html");;
        }
        passport.authenticate("local")(
            req, res, function () {
                res.sendFile(__dirname + "/views/homepage.html");
            });
    });
});

app.listen(1337)

my user.js

const mongoose = require('mongoose');
const Joi = require('joi');

const userSchema = new mongoose.Schema({
    username: {
        type: String,
        unique: true,
        required: true
    },
    password: {
        type: String,
        max: 1024,
        min: 6,
        required: true
    }

});

function validateUser(user) {
    const schema = {
        username: Joi.string().min(5).max(50).required(),
        email: Joi.string().min(5).max(255).required().email(),
        password: Joi.string().min(5).max(255).required()
    };
    return Joi.validate(user, schema);
}

module.exports = mongoose.model('User', userSchema);
exports.validate = validateUser;

and my login.html

<!DOCTYPE html>

    <link rel="stylesheet" type = "text/css" href="login.css" />
    <title>Global Teller Machine 2.0</title>
    <meta charset="utf-8" />

                Welcome to GTM 2.0

Please sign in to begin

        <form action="/login" method="post">

                Username

                <input type="text" placeholder="Enter Username" name="username" id="username" required>

                    Password

                    <input type="password" placeholder="Enter Password" name="password" id="password" required>

                <input id="data" type="submit" value="Login" />

        </form>


问:
Is it possible to filter by account type and date?
I have two datasets, the products and services tables.

Basically, the business logic is: I acquire products (I can have multiple products but only 2 active the rest have to be in "inactive status") and I can subscribe services. The service is like an insurance for the product that I acquire, and I can have more than one service per account.

Note: active products have a start date and no end date. Inactive products have a start date and an end date.

I don't know if what I need is possible to develop in Power Bi, but what I want is two filters, one is the date and the other is the account type.

I tried to develop an example, in Power Bi. I have the products table, services table and I created a new table (manually) that gives me the account type.

The example has 3 accounts (imagine we are in January 2023) :

1 account with 2 inactive products and 2 inactive services;

1 account with 1 active product and 1 active service;

1 account with 1 inactive product without services.

If I filter by July 2022 and select "All" for the Account Type filter, what I pretend to watch is a donut chart with 1 service A and 2 service B.

If I filter by "Dual" (and the filter date remains unchanged) I want to watch 1 service A and 1 service B.

To conclude, what I need to know is if it is possible to make this account type table (or another approach that allows me to have the account type) and then if it is possible to have this filter and that it can relate to the metric that I created of "# active services" (in the example that I develop it is not related well because despite the connection between tables there is no date factor which causes the results to be incorrect).

Product Table (Code):

```<code>let
Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMlTSUTIw1AciIwMjIyDH2FDf0AjGMQXigKL8lNLkEgVHLCoNzCGcWB1CJhmbIRnlBFVqhkUpyCgjqLwxTB6ITLC5BaEApM0Yw1gDfUMDGMfCFK8LEEpjYwE=", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [acct_id = _t, acct_start_date = _t, acct_end_date = _t, product_id = _t, product_name = _t, product_start_date = _t, product_end_date = _t]),
#"Changed Type" = Table.TransformColumnTypes(Source,{{"acct_id", Int64.Type}, {"acct_start_date", type date}, {"acct_end_date", type date}, {"product_id", Int64.Type}, {"product_name", type text}, {"product_start_date", type date}, {"product_end_date", type date}})
in
#"Changed Type"
</code>```

product_table

Service Table (Code):

```<code>let
Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMlTSUTIw1AciIwMjIyDH2FDf0AjGMTEFEsGpRWWZyakKjniUxuoQMsrCDMkoJ6hSMxxGGUHljWHyQGRpiWaAoSmygthYAA==", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [acct_id = _t, acct_start_date = _t, acct_end_date = _t, service_id = _t, service_name = _t, service_start_date = _t, service_end_date = _t]),
#"Changed Type" = Table.TransformColumnTypes(Source,{{"acct_id", Int64.Type}, {"acct_start_date", type date}, {"acct_end_date", type date}, {"service_id", Int64.Type}, {"service_name", type text}, {"service_start_date", type date}, {"service_end_date", type date}})
in
#"Changed Type"
</code>```

service_table

Account Table (Code):

```<code>let
Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMlTSUTIw1AciIwMjIyDH2FDf0AjG8c3Py1fQVQgoyk8pTS5RcMSi2MAUwonVIWSYS2liDlSBGbIB5sQagOYaJ6hiCyyKQYYZQeWNYfK4PYRQAtJojOFKA31DAwKuwKY4NhYA", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [acct_id = _t, acct_start_date = _t, acct_end_date = _t, account_type = _t, start_date = _t, end_date = _t]),
#"Changed Type" = Table.TransformColumnTypes(Source,{{"acct_id", Int64.Type}, {"acct_start_date", type date}, {"acct_end_date", type date}, {"account_type", type text}, {"start_date", type date}, {"end_date", type date}})
in
#"Changed Type"
</code>```

account_type_table

Dim_Date:

dim_date_layout

Measure:

```<code># active_services =
VAR Data =
    MAX(Dim_Date[Date])
RETURN
CALCULATE(
    DISTINCTCOUNT(fact_services_table[service_id]),
    ALL(dim_Date[Date]),
    fact_services_table[service_start_date] <> BLANK(),
    fact_services_table[service_start_date] <= Data,
        OR(
            fact_services_table[service_end_date] > Data,
            fact_services_table[service_end_date] = BLANK()
        )
)
</code>```

Model:

relationships

Final Output:

account_type_all_filter

account_type_dual_filter

Body:
I have two datasets, the products and services tables.

Basically, the business logic is: I acquire products (I can have multiple products but only 2 active the rest have to be in "inactive status") and I can subscribe services. The service is like an insurance for the product that I acquire, and I can have more than one service per account.

Note: active products have a start date and no end date. Inactive products have a start date and an end date.

I don't know if what I need is possible to develop in Power Bi, but what I want is two filters, one is the date and the other is the account type.

I tried to develop an example, in Power Bi. I have the products table, services table and I created a new table (manually) that gives me the account type.

The example has 3 accounts (imagine we are in January 2023) :

1 account with 2 inactive products and 2 inactive services;

1 account with 1 active product and 1 active service;

1 account with 1 inactive product without services.

If I filter by July 2022 and select "All" for the Account Type filter, what I pretend to watch is a donut chart with 1 service A and 2 service B.

If I filter by "Dual" (and the filter date remains unchanged) I want to watch 1 service A and 1 service B.

To conclude, what I need to know is if it is possible to make this account type table (or another approach that allows me to have the account type) and then if it is possible to have this filter and that it can relate to the metric that I created of "# active services" (in the example that I develop it is not related well because despite the connection between tables there is no date factor which causes the results to be incorrect).

Product Table (Code):

let
Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMlTSUTIw1AciIwMjIyDH2FDf0AjGMQXigKL8lNLkEgVHLCoNzCGcWB1CJhmbIRnlBFVqhkUpyCgjqLwxTB6ITLC5BaEApM0Yw1gDfUMDGMfCFK8LEEpjYwE=", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [acct_id = _t, acct_start_date = _t, acct_end_date = _t, product_id = _t, product_name = _t, product_start_date = _t, product_end_date = _t]),
#"Changed Type" = Table.TransformColumnTypes(Source,{{"acct_id", Int64.Type}, {"acct_start_date", type date}, {"acct_end_date", type date}, {"product_id", Int64.Type}, {"product_name", type text}, {"product_start_date", type date}, {"product_end_date", type date}})
in
#"Changed Type"

product_table

Service Table (Code):

let
Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMlTSUTIw1AciIwMjIyDH2FDf0AjGMTEFEsGpRWWZyakKjniUxuoQMsrCDMkoJ6hSMxxGGUHljWHyQGRpiWaAoSmygthYAA==", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [acct_id = _t, acct_start_date = _t, acct_end_date = _t, service_id = _t, service_name = _t, service_start_date = _t, service_end_date = _t]),
#"Changed Type" = Table.TransformColumnTypes(Source,{{"acct_id", Int64.Type}, {"acct_start_date", type date}, {"acct_end_date", type date}, {"service_id", Int64.Type}, {"service_name", type text}, {"service_start_date", type date}, {"service_end_date", type date}})
in
#"Changed Type"

service_table

Account Table (Code):

let
Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMlTSUTIw1AciIwMjIyDH2FDf0AjG8c3Py1fQVQgoyk8pTS5RcMSi2MAUwonVIWSYS2liDlSBGbIB5sQagOYaJ6hiCyyKQYYZQeWNYfK4PYRQAtJojOFKA31DAwKuwKY4NhYA", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [acct_id = _t, acct_start_date = _t, acct_end_date = _t, account_type = _t, start_date = _t, end_date = _t]),
#"Changed Type" = Table.TransformColumnTypes(Source,{{"acct_id", Int64.Type}, {"acct_start_date", type date}, {"acct_end_date", type date}, {"account_type", type text}, {"start_date", type date}, {"end_date", type date}})
in
#"Changed Type"

account_type_table

Dim_Date:

dim_date_layout

Measure:

# active_services =
VAR Data =
    MAX(Dim_Date[Date])
RETURN
CALCULATE(
    DISTINCTCOUNT(fact_services_table[service_id]),
    ALL(dim_Date[Date]),
    fact_services_table[service_start_date] <> BLANK(),
    fact_services_table[service_start_date] <= Data,
        OR(
            fact_services_table[service_end_date] > Data,
            fact_services_table[service_end_date] = BLANK()
        )
)

Model:

relationships

Final Output:

account_type_all_filter

account_type_dual_filter


问:
React Native: How do I change the scroll position of a ScrollView when the element is not visible?
I have a horizontal FlatList which renders a list of vertical ScrollView cards.

When I scroll the FlatList, I would like the ScrollView cards to reset their scroll position to the top.  I do not want to reset the scroll position of the larger FlatList, instead, on each FlatList scroll, I want each individual ScrollView to scrollToStart if that ScrollView is not visible on the screen.

It would be something like this, probably using refs...

```<code>const onFlatlistScroll = { (scrollViewCard) => {
  if (scrollViewCard.visible !== true && scrollViewCard.scrollPositionY !== 0) {
    scrollViewCard.scrollTo({
      'x': 0,
      'y': 0,
      animated: true,
    });
  }
}};
</code>```

I tried using the FlatList's onViewableItemsChanged and viewabilityConfig properties to tell if an individual scrollViewCard was not visible, however, I have an accessibility feature that changes the fontFamily and fontSize properties of Text elements with an onPress (to make text easier to read) and this onPress event throws an error with onViewableItemsChanged for 'on the fly changes not supported'.

I also see that the ScrollView property scrollsToTop does this when the device's StatusBar is pressed/tapped, but I am unsure of how to trigger this event with something other than an actual user tap on the StatusBar and that might be an inefficient solution to try and simulate a tap or hack into this property, but if someone knows more about this property/feature and can offer input that would be appreciated.

Body:
I have a horizontal FlatList which renders a list of vertical ScrollView cards.

When I scroll the FlatList, I would like the ScrollView cards to reset their scroll position to the top.  I do not want to reset the scroll position of the larger FlatList, instead, on each FlatList scroll, I want each individual ScrollView to scrollToStart if that ScrollView is not visible on the screen.

It would be something like this, probably using refs...

const onFlatlistScroll = { (scrollViewCard) => {
  if (scrollViewCard.visible !== true && scrollViewCard.scrollPositionY !== 0) {
    scrollViewCard.scrollTo({
      'x': 0,
      'y': 0,
      animated: true,
    });
  }
}};

I tried using the FlatList's onViewableItemsChanged and viewabilityConfig properties to tell if an individual scrollViewCard was not visible, however, I have an accessibility feature that changes the fontFamily and fontSize properties of Text elements with an onPress (to make text easier to read) and this onPress event throws an error with onViewableItemsChanged for 'on the fly changes not supported'.

I also see that the ScrollView property scrollsToTop does this when the device's StatusBar is pressed/tapped, but I am unsure of how to trigger this event with something other than an actual user tap on the StatusBar and that might be an inefficient solution to try and simulate a tap or hack into this property, but if someone knows more about this property/feature and can offer input that would be appreciated.


问:
Is there a library to apply a Mean Curvature Blur in Python?
In GIMP there is a blur called Mean Curvature. I‘d like to apply a filter like that on a picture in a python script but don‘t find a library/module that implements this algorithm. Does anybody know one?
Thank you!

I searched for an implementation of a Mean Curvature Blur in python but didn’t find one.


问:
Priority queue doesnt work as it must if I remove a line of code
I have come up with this code to implement a priority queue however I dont understand why it works. I just got lucky I guess. I had this gut feeling I had to put there. Anyway I  put a comment below the line highlighting the code I dont understand.

class queueNode:
    def __init__(self,val,nextNode,prior):
        self.val = val
        self.nextNode = nextNode
        self.prior = prior

class priorityQueue:
    def __init__(self,baseNode):
        self.baseNode = baseNode

    def addNode(self,insertedNode):
        current = self.baseNode

#             vvvvvvvvvvvv
        while current.next and current.prior > insertedNode.prior:
#             ^^^^^^^^^^^^

            current = current.nextNode
        target = current.nextNode
        current.nextNode = insertedNode
        insertedNode.nextNode = target

    def deleteNode():
        current = self.baseNode
        target = current.nextNode
        self.baseNode = target
        del current

    def print(self):
        current = self.baseNode
        while current:
            print("Value:",current.val+" ")
            print("Priority:\n",current.prior)
            current = current.nextNode

q1 = queueNode("A",None,1)
myQueue = priorityQueue(q1)
q2 = queueNode("B",None,1)
q3 = queueNode("C",None,0)
q4 = queueNode("D",None,0)
q5 = queueNode("E",None,1)

myQueue.addNode(q2)
myQueue.addNode(q3)
myQueue.addNode(q4)
myQueue.addNode(q5)

myQueue.print()
```

When I remove the highlighted code it shows me an error that NoneType doesnt contain an argument named prior, I guess I am running into some NoneType Exception but the code is very complicated and cannot understand why?

Body:
I have come up with this code to implement a priority queue however I dont understand why it works. I just got lucky I guess. I had this gut feeling I had to put there. Anyway I  put a comment below the line highlighting the code I dont understand.

class queueNode:
    def __init__(self,val,nextNode,prior):
        self.val = val
        self.nextNode = nextNode
        self.prior = prior

class priorityQueue:
    def __init__(self,baseNode):
        self.baseNode = baseNode

    def addNode(self,insertedNode):
        current = self.baseNode

#             vvvvvvvvvvvv
        while current.next and current.prior > insertedNode.prior:
#             ^^^^^^^^^^^^

            current = current.nextNode
        target = current.nextNode
        current.nextNode = insertedNode
        insertedNode.nextNode = target

    def deleteNode():
        current = self.baseNode
        target = current.nextNode
        self.baseNode = target
        del current

    def print(self):
        current = self.baseNode
        while current:
            print("Value:",current.val+" ")
            print("Priority:\n",current.prior)
            current = current.nextNode

q1 = queueNode("A",None,1)
myQueue = priorityQueue(q1)
q2 = queueNode("B",None,1)
q3 = queueNode("C",None,0)
q4 = queueNode("D",None,0)
q5 = queueNode("E",None,1)

myQueue.addNode(q2)
myQueue.addNode(q3)
myQueue.addNode(q4)
myQueue.addNode(q5)

myQueue.print()

When I remove the highlighted code it shows me an error that NoneType doesnt contain an argument named prior, I guess I am running into some NoneType Exception but the code is very complicated and cannot understand why?