答:
Thanks to @AndrewGillreathBrown for a sample data set missing from your question.

With the (same) data in a data.frame named df, we can use base R function aggregate to answer this:

```<code>> aggregate(active_cases ~ date + state, df, sum)
        date      state active_cases
1 2022-01-31    Alabama         6240
2 2022-02-01    Alabama         6240
3 2022-01-31   New York        10004
4 2022-02-01   New York        10004
5 2022-01-31 Washington         3384
6 2022-02-01 Washington         3384
>
</code>```

Title: starting my second data project and already ran into something I can't figure out

Body: So I have a table with a column for active covid cases and another one for the city the cases are reported in. Now, I need to somehow sum all the cases for a given state on each day for each state. For example, I have 2 years of daily active covid cases from 100 cities. I would like to put them into "state buckets" for my analysis. Is there a way to do this in R? Appreciate the help!

Body:
Thanks to @AndrewGillreathBrown for a sample data set missing from your question.

With the (same) data in a data.frame named df, we can use base R function aggregate to answer this:

> aggregate(active_cases ~ date + state, df, sum)
        date      state active_cases
1 2022-01-31    Alabama         6240
2 2022-02-01    Alabama         6240
3 2022-01-31   New York        10004
4 2022-02-01   New York        10004
5 2022-01-31 Washington         3384
6 2022-02-01 Washington         3384
>


来源: stackexchange

问:
Create a Google Doc file directly in a Google Drive folder
How do I create a Google document in a Google Drive folder?

I know that I can create a file in a folder like this.

```<code>var folder = DriveApp.createFolder("A Folder")
folder.createFile("filename.file", "Some text")
</code>```

But how I can create a document in a folder using Google Apps Script.

答:
You can also use the Drive App to create a copy of a Google document (e.g. a template)

use this:

```<code>DriveApp.getFileById(templateFileId).makeCopy(name, destination);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How do I create a Google document in a Google Drive folder?

I know that I can create a file in a folder like this.

var folder = DriveApp.createFolder("A Folder")
folder.createFile("filename.file", "Some text")

But how I can create a document in a folder using Google Apps Script.

Body:
You can also use the Drive App to create a copy of a Google document (e.g. a template)

use this:

DriveApp.getFileById(templateFileId).makeCopy(name, destination);


问:
"NotSupportedError: Failed to load because no supported source was found." - flutter audioplayers on web debugging
I'm trying to play a sound when a button is clicked, and decided to use the "audioplayers" library for it. The problem is that when I run my app on the well I get this weird error-

```<code>Error: NotSupportedError: Failed to load because no supported source was found.
    at Object.createErrorWithStack (http://localhost:49201/dart_sdk.js:5076:12)
    at Object._rethrow (http://localhost:49201/dart_sdk.js:40477:16)
    at async._AsyncCallbackEntry.new.callback (http://localhost:49201/dart_sdk.js:40473:13)
    at Object._microtaskLoop (http://localhost:49201/dart_sdk.js:40330:13)
    at _startMicrotaskLoop (http://localhost:49201/dart_sdk.js:40336:13)
    at http://localhost:49201/dart_sdk.js:35811:9
</code>```

I dont't really know why this is happening. I'll try testing this on an emulator and see how it goes. But for now here's the code-

Here's the code-

```<code>class _PopScreenState extends State<PopScreen> {
  late String currentPath;
  AudioCache player = new AudioCache();      //relevant

  void initState() {
    super.initState();
    currentPath = normalPaths[widget.id];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          backgroundColor: animalColorThemes[widget.id],
          title: Text(
            animalData[widget.id][0],
          ),
          centerTitle: true,
        ),
        body: GestureDetector(
          onTapDown: (e) {
            player.play("assets/pop1.mp3");           //relevant
            setState(() {
              currentPath = activePaths[widget.id];
            });
          },
          onTapUp: (e) {
            setState(() {
              currentPath = normalPaths[widget.id];
            });
          },
          child: Stack(
            children: [
              Container(
                decoration: BoxDecoration(
                  image: DecorationImage(
                    fit: BoxFit.fill,
                    image: AssetImage(
                      currentPath,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ));
  }
}

</code>```

答:
first of all you have to check you're pubspec.yaml file and register assets folder on it like this:

```<code>flutter:
        assets:
                - assets/audio/
</code>```

be careful about space in this file.
then you can use this library too: audio player

the second cuase  this error is spelling you file name.

Body:
I'm trying to play a sound when a button is clicked, and decided to use the "audioplayers" library for it. The problem is that when I run my app on the well I get this weird error-

Error: NotSupportedError: Failed to load because no supported source was found.
    at Object.createErrorWithStack (http://localhost:49201/dart_sdk.js:5076:12)
    at Object._rethrow (http://localhost:49201/dart_sdk.js:40477:16)
    at async._AsyncCallbackEntry.new.callback (http://localhost:49201/dart_sdk.js:40473:13)
    at Object._microtaskLoop (http://localhost:49201/dart_sdk.js:40330:13)
    at _startMicrotaskLoop (http://localhost:49201/dart_sdk.js:40336:13)
    at http://localhost:49201/dart_sdk.js:35811:9

I dont't really know why this is happening. I'll try testing this on an emulator and see how it goes. But for now here's the code-

Here's the code-

class _PopScreenState extends State<PopScreen> {
  late String currentPath;
  AudioCache player = new AudioCache();      //relevant

  void initState() {
    super.initState();
    currentPath = normalPaths[widget.id];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          backgroundColor: animalColorThemes[widget.id],
          title: Text(
            animalData[widget.id][0],
          ),
          centerTitle: true,
        ),
        body: GestureDetector(
          onTapDown: (e) {
            player.play("assets/pop1.mp3");           //relevant
            setState(() {
              currentPath = activePaths[widget.id];
            });
          },
          onTapUp: (e) {
            setState(() {
              currentPath = normalPaths[widget.id];
            });
          },
          child: Stack(
            children: [
              Container(
                decoration: BoxDecoration(
                  image: DecorationImage(
                    fit: BoxFit.fill,
                    image: AssetImage(
                      currentPath,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ));
  }
}

Body:
first of all you have to check you're pubspec.yaml file and register assets folder on it like this:

flutter:
        assets:
                - assets/audio/

be careful about space in this file.
then you can use this library too: audio player

the second cuase  this error is spelling you file name.


问:
checking if list contains same element in straight row
so,I have a list [5. 5. 5. 5. 0. 0.] I want to check if it contains same elements in straight row (atleast 4 )

I came up with this

```<code>for i in list:
    w = []
    for x in range(len(i)-4):
        if (i[x] == i[x+1] == i[x+2] == i[x+3] != 0) :
            print(i[x])
            break
</code>```

I gives me desired output,

but , what would the efficient way to achieving the same result ,without much looping ?

答:
If you want to solve this problem without any library, you can iterate the list and count the Continuous elements:

a = [
    [5, 5, 5, 5, 0, 0],
    [1, 2, 3, 4, 5, 6],
    [0, 1, 1, 1, 0, 0, 0],
    [0, 0, 1, 1, 1, 1, 0],
    [0, 1, 2, 2, 2, 2],
    [1, 1, 1, 1]
]

def contains_n(n, l):
    c = 0
    last = ""
    for v in l:
        if v == last:
            c += 1
        else:
            c = 1
            last = v
        if c == n:
            return True
    return False

for v in a:
    print(contains_n(4, v))
```
<p>The output will be:</p>
<pre class="lang-python prettyprint-override"><code>True
False
False
True
True
True
</code>```

Body:
so,I have a list [5. 5. 5. 5. 0. 0.] I want to check if it contains same elements in straight row (atleast 4 )

I came up with this

for i in list:
    w = []
    for x in range(len(i)-4):
        if (i[x] == i[x+1] == i[x+2] == i[x+3] != 0) :
            print(i[x])
            break

I gives me desired output,

but , what would the efficient way to achieving the same result ,without much looping ?

Body:
If you want to solve this problem without any library, you can iterate the list and count the Continuous elements:

a = [
    [5, 5, 5, 5, 0, 0],
    [1, 2, 3, 4, 5, 6],
    [0, 1, 1, 1, 0, 0, 0],
    [0, 0, 1, 1, 1, 1, 0],
    [0, 1, 2, 2, 2, 2],
    [1, 1, 1, 1]
]

def contains_n(n, l):
    c = 0
    last = ""
    for v in l:
        if v == last:
            c += 1
        else:
            c = 1
            last = v
        if c == n:
            return True
    return False

for v in a:
    print(contains_n(4, v))

The output will be:

True
False
False
True
True
True


问:
Can’t find all page tables when web scraping using r
I am trying to scrape a table of tide data collected at 6 minute interval from a NOAA site using r.
I have tried a few different approaches but none seem to be able to find the table I am looking for:

```<code>page_adress<-"https://tidesandcurrents.noaa.gov/noaatidepredictions.html?id=1612480&units=standard&bdate=20220204&edate=20220205&timezone=LST&clock=12hour&datum=MLLW&interval=6&action=data"

library(htmltab)
htmltab(doc = page_adress, which=1, header=0)

library(rvest)
html <- read_html(page_adress)

html %>%
  html_nodes("table") %>%
  .[[1]] %>%
  html_table()
</code>```

Both approaches can only find the short summary table on top of the page, but not the larger table requested.

```<code>> 1  5:18 AM high 1.89 ft.
2 12:11 PM  low 0.28 ft.
3  6:03 PM high 1.19 ft.
4 11:11 PM  low 0.67 ft.
</code>```

If I inspect the code, I can see the long table data in the html document.

I am proficient to r but new to scraping, so I may be missing something obvious… any help or guidance would be highly appreciated!

Body:
I am trying to scrape a table of tide data collected at 6 minute interval from a NOAA site using r.
I have tried a few different approaches but none seem to be able to find the table I am looking for:

page_adress<-"https://tidesandcurrents.noaa.gov/noaatidepredictions.html?id=1612480&units=standard&bdate=20220204&edate=20220205&timezone=LST&clock=12hour&datum=MLLW&interval=6&action=data"

library(htmltab)
htmltab(doc = page_adress, which=1, header=0)

library(rvest)
html <- read_html(page_adress)

html %>%
  html_nodes("table") %>%
  .[[1]] %>%
  html_table()

Both approaches can only find the short summary table on top of the page, but not the larger table requested.

> 1  5:18 AM high 1.89 ft.
2 12:11 PM  low 0.28 ft.
3  6:03 PM high 1.19 ft.
4 11:11 PM  low 0.67 ft.

If I inspect the code, I can see the long table data in the html document.

I am proficient to r but new to scraping, so I may be missing something obvious… any help or guidance would be highly appreciated!

Body:
Using jsonlite package,

url = 'https://api.tidesandcurrents.noaa.gov/api/prod/datagetter?product=predictions&begin_date=20220203&end_date=20220206&datum=MLLW&station=1612480&time_zone=LST&units=english&interval=6&format=json&application=NOS.COOPS.TAC.TidePred'

library(jsonlite)
fromJSON(url)
$predictions
                   t      v
1   2022-02-03 00:00  0.431
2   2022-02-03 00:06  0.485
3   2022-02-03 00:12  0.540
4   2022-02-03 00:18  0.596
5   2022-02-03 00:24  0.653
6   2022-02-03 00:30  0.710
7   2022-02-03 00:36  0.768
8   2022-02-03 00:42  0.826
9   2022-02-03 00:48  0.885
10  2022-02-03 00:54  0.944
11  2022-02-03 01:00  1.003


问:
Laravel observer for pivot table
I've got a observer that has a update method:

ObserverServiceProvider.php

```<code>public function boot()
{
    Relation::observe(RelationObserver::class);
}
</code>```

RelationObserver.php

```<code>public function updated(Relation $relation)
{
    $this->cache->tags(Relation::class)->flush();
}
</code>```

So when I update a relation in my controller:

```<code>public function update(Request $request, Relation $relation)
{
     $relation->update($request->all()));
     return back();
}
</code>```

Everything is working as expected. But now I've got a pivot table. A relation belongsToMany products.

So now my controller method looks like this:

```<code>public function update(Request $request, Relation $relation)
{
    if(empty($request->products)) {
        $relation->products()->detach();
    } else {
        $relation->products()->sync(collect($request->products)->pluck('id'));
    }

    $relation->update($request->all());

    return back();
}
</code>```

The problem is that the observer is not triggered anymore if I only add or remove products.

How can I trigger the observer when the pivot table updates aswel?

Thanks

答:
Just add:

```<code>public $afterCommit = true;
</code>```

at the beginning of the observer class.. It will wait until the transactions are done, then performs your sync which should then work fine..

Please check Laravel's documentation for that.

It seems this solutions was just added in Laravel 8.

ContentLicense: CC BY-SA 3.0

Title: Laravel observer for pivot table

Body:
I've got a observer that has a update method:

ObserverServiceProvider.php

public function boot()
{
    Relation::observe(RelationObserver::class);
}

RelationObserver.php

public function updated(Relation $relation)
{
    $this->cache->tags(Relation::class)->flush();
}

So when I update a relation in my controller:

public function update(Request $request, Relation $relation)
{
     $relation->update($request->all()));
     return back();
}

Everything is working as expected. But now I've got a pivot table. A relation belongsToMany products.

So now my controller method looks like this:

public function update(Request $request, Relation $relation)
{
    if(empty($request->products)) {
        $relation->products()->detach();
    } else {
        $relation->products()->sync(collect($request->products)->pluck('id'));
    }

    $relation->update($request->all());

    return back();
}

The problem is that the observer is not triggered anymore if I only add or remove products.

How can I trigger the observer when the pivot table updates aswel?

Thanks

Body:
Just add:

public $afterCommit = true;

at the beginning of the observer class.. It will wait until the transactions are done, then performs your sync which should then work fine..

Please check Laravel's documentation for that.

It seems this solutions was just added in Laravel 8.


问:
Addition on HashSet of KeyValuePair
I have a list of entries. Each entry contains a string and a numerical value. The same string  can appear one or more times in a list and it can have a different numerical value. be I am looking for an elegant way to process the list. The end result should be a list of unique pairs of string and (sum of values for the string). Each unique string should be associated with the sum of all numerical values for the string. I consider creating a HashSet<KeyValuePair<string, double>> and to add each string to the HashSet. But I am not sure how to add all values together in a single loop. The code below works, but it is inefficient.</p>
```<code>        SortedSet<string> symbols = new SortedSet<string>();
        HashSet<KeyValuePair<string, double>> results = new HashSet<KeyValuePair<string, double>>();
        string file = openFileDialog1.FileName;
        string[] lines = File.ReadAllLines(file);

        foreach(string line in lines) {
            string[] values = line.Split('\t');
            string symbol = values[0].Trim();
            symbols.Add(symbol);
        }

        foreach(string uniqueSymbol in symbols) {
            double value = 0;
            foreach(string line in lines) {
                string[] values = line.Split('\t');
                string symbol = values[0].Trim();
                string sProfit = values[7].Trim();
                double fProfit = Convert.ToDouble(sProfit);

                if(symbol == uniqueSymbol) {
                    value += fProfit;
                }
            }

            results.Add(new KeyValuePair<string, double>(uniqueSymbol, value));
        }
</code>```

答:
I’m not sure why you need a to be using a HashSet for something that certainly looks the a job for a Dictionary.

Here’s how I would approach populating such a dictionary:

```<code>Dictionary<string, double> result = new Dictionary<string, double>();

foreach (string line in lines)
{
    string[] values = line.Split(“\t”);
    string symbol = values[0].Trim();
    double profit = Convert.ToDouble(values[7].Trim());
    result.TryGetValue(symbol, out double _profit);
    result[symbol] = _profit + profit;
}
</code>```

If you needed to extract those into a HashSet that should be easy enough.

Title: Addition on HashSet of KeyValuePair

Body:
I have a list of entries. Each entry contains a string and a numerical value. The same string  can appear one or more times in a list and it can have a different numerical value. be I am looking for an elegant way to process the list. The end result should be a list of unique pairs of string and (sum of values for the string). Each unique string should be associated with the sum of all numerical values for the string. I consider creating a HashSet<KeyValuePair<string, double>> and to add each string to the HashSet. But I am not sure how to add all values together in a single loop. The code below works, but it is inefficient.

        SortedSet<string> symbols = new SortedSet<string>();
        HashSet<KeyValuePair<string, double>> results = new HashSet<KeyValuePair<string, double>>();
        string file = openFileDialog1.FileName;
        string[] lines = File.ReadAllLines(file);

        foreach(string line in lines) {
            string[] values = line.Split('\t');
            string symbol = values[0].Trim();
            symbols.Add(symbol);
        }

        foreach(string uniqueSymbol in symbols) {
            double value = 0;
            foreach(string line in lines) {
                string[] values = line.Split('\t');
                string symbol = values[0].Trim();
                string sProfit = values[7].Trim();
                double fProfit = Convert.ToDouble(sProfit);

                if(symbol == uniqueSymbol) {
                    value += fProfit;
                }
            }

            results.Add(new KeyValuePair<string, double>(uniqueSymbol, value));
        }

Body:
I’m not sure why you need a to be using a HashSet for something that certainly looks the a job for a Dictionary.

Here’s how I would approach populating such a dictionary:

Dictionary<string, double> result = new Dictionary<string, double>();

foreach (string line in lines)
{
    string[] values = line.Split(“\t”);
    string symbol = values[0].Trim();
    double profit = Convert.ToDouble(values[7].Trim());
    result.TryGetValue(symbol, out double _profit);
    result[symbol] = _profit + profit;
}

If you needed to extract those into a HashSet that should be easy enough.


问:
Why doesn't Java's JIT compiler translate everything to native code?
I have been looking into the Java JIT compiler and i cannot figure out why some of the code is still interpreted. Why doesn't the JIT compiler translate everything to native code? Interpretation is much slower, am I missing something?</p>

答:
It's all a matter of tradeoffs

the time taken to compile + execute code can be longer than the time to interpret once

you can often optimise things much more efficiently if you have statistics on branching, etc

some things can't be compiled (anything that does RTTI, probably)

some things you don't want compiled (line numbers for stack traces, etc)

I'm sure there's others.


问:
Multiple commands produce error in Xcode 13
I have been stuck on this bug for quite a while now so any help would be appreciated. When I try to build my app I keep getting the following build error:

Multiple commands produce '/Users/my_user_name/Library/Developer/Xcode/DerivedData/Expense_Tracker_Final-aujeprcwgnjmizeaueitvhpegrzf/Build/Products/Debug-iphonesimulator/Expense Tracker Final.app':

Target 'Expense Tracker Final' has create directory command with output '/Users/my_user_name/Library/Developer/Xcode/DerivedData/Expense_Tracker_Final-aujeprcwgnjmizeaueitvhpegrzf/Build/Products/Debug-iphonesimulator/Expense Tracker Final.app'

That command depends on command in Target 'Expense Tracker Final': script phase “[CP] Copy Pods Resources”

I have tried solution that have been recommended on other stack overflow questions such as deleting certain files from the [CP] Copy Pods Resources, but nothing seems to be working. Could someone please help me I'm really lost.

答:
Select Targets -> BuildPhases.

There you saw Copy Bundle Resources. Just remove the duplicate file that is creating an error by selecting that file and clicking on the minus icon and if info.plist is present there just remove it also.


问:
Next.js on Vercel, is server code on single Lambda?
I found this quote on the Vercel website:

When using Next.js, Vercel optimizes Serverless Function output for server-rendered pages and API Routes. All functions will be created inside the same bundle (or in multiple chunks if greater than 50mb). This helps reduce cold starts since the bundled function is more likely warm

But is this also true for getServerSideProps?

I have a small project with an API and another page that loads the data with getServerSideProps. When the first API is done. I would except the next page with the getServerSideProps would be fast, but that also seems to have a cold boot.
The second time everything is fast.

答:
You can also use caching headers inside getServerSideProps and API Routes for dynamic responses. For example, using stale-while-revalidate.

if you use Vercel to host your frontend, with one line of code you can take advantage of the stale-while-revalidate cache strategy which has very similar behaviour to getStaticProps when using revalidate.

```<code>// This value is considered fresh for ten seconds (s-maxage=10).
// If a request is repeated within the next 10 seconds, the previously
// cached value will still be fresh. If the request is repeated before 59 seconds,
// the cached value will be stale but still render (stale-while-revalidate=59).
//
// In the background, a revalidation request will be made to populate the cache
// with a fresh value. If you refresh the page, you will see the new value.
export async function getServerSideProps({ req, res }) {
  res.setHeader(
    'Cache-Control',
    'public, s-maxage=10, stale-while-revalidate=59'
  )

  return {
    props: {},
  }
}
</code>```

Check the docs: https://nextjs.org/docs/going-to-production#caching

But it is important to know when to use getServerSideProps or api urls in next.js

When to use getServerSideProps

The getServerSideProps function fetches data each time a user requests the page. It will fetch the data before sending the page to the client If the client makes a subsequent request, the data will be fetched again. In these cases it is helpful to use:

SEO is important for the page

The content that is fetched is important and updates frequently

When we want to fetch data that relates to the user's cookies/activity and is consequently not possible to cache. Websites with user authentication features end up relying on getServerSideProps a lot to make sure users are properly signed in before fulfilling a request.

If the page is not SEO critical, for example, if you need to fetch the current users for the admin, you do not need to use getServerSideProps. However, if you are fetching the shopping items for your home page, it is good practice to use getServerSideProps.

When to use api functions

It is important to understand that some websites that we are building do not just need Html pages that are being served back to the users upon requests. You might for example have a feature on your website that allows users to submit feedback or signup for a newsletter. So when a user clicks on such a button to for example signup for a newsletter, think about what happens behind the scenes when we signup for newsletter.

We need to send data to some server to store that entered newsletter email addressd in some database, and that request being sent is not about fetching a site, it is about storing data. We do not want to get a Html page, Instead we want to send that user entered data to some database. that is why we use API's for. there are different types of api but the main idea is same. we have a server that exposes some certain urls. Those urls are not just sending html data, but they are about accepting some data and sending back responses with any kind of data.

So Api routes are special kind of Urls, which you can add to your next.js application, which are not about getting a standard browser request and sending back a prerendered html page, but which are about getting data, using data maybe storing data in some database and sending back data in any form of your choice.

Body:
You can also use caching headers inside getServerSideProps and API Routes for dynamic responses. For example, using stale-while-revalidate.

if you use Vercel to host your frontend, with one line of code you can take advantage of the stale-while-revalidate cache strategy which has very similar behaviour to getStaticProps when using revalidate.

// This value is considered fresh for ten seconds (s-maxage=10).
// If a request is repeated within the next 10 seconds, the previously
// cached value will still be fresh. If the request is repeated before 59 seconds,
// the cached value will be stale but still render (stale-while-revalidate=59).
//
// In the background, a revalidation request will be made to populate the cache
// with a fresh value. If you refresh the page, you will see the new value.
export async function getServerSideProps({ req, res }) {
  res.setHeader(
    'Cache-Control',
    'public, s-maxage=10, stale-while-revalidate=59'
  )

  return {
    props: {},
  }
}

Check the docs: https://nextjs.org/docs/going-to-production#caching

But it is important to know when to use getServerSideProps or api urls in next.js

When to use getServerSideProps

The getServerSideProps function fetches data each time a user requests the page. It will fetch the data before sending the page to the client If the client makes a subsequent request, the data will be fetched again. In these cases it is helpful to use:

SEO is important for the page

The content that is fetched is important and updates frequently

When we want to fetch data that relates to the user's cookies/activity and is consequently not possible to cache. Websites with user authentication features end up relying on getServerSideProps a lot to make sure users are properly signed in before fulfilling a request.

If the page is not SEO critical, for example, if you need to fetch the current users for the admin, you do not need to use getServerSideProps. However, if you are fetching the shopping items for your home page, it is good practice to use getServerSideProps.

When to use api functions

It is important to understand that some websites that we are building do not just need Html pages that are being served back to the users upon requests. You might for example have a feature on your website that allows users to submit feedback or signup for a newsletter. So when a user clicks on such a button to for example signup for a newsletter, think about what happens behind the scenes when we signup for newsletter.

We need to send data to some server to store that entered newsletter email addressd in some database, and that request being sent is not about fetching a site, it is about storing data. We do not want to get a Html page, Instead we want to send that user entered data to some database. that is why we use API's for. there are different types of api but the main idea is same. we have a server that exposes some certain urls. Those urls are not just sending html data, but they are about accepting some data and sending back responses with any kind of data.

So Api routes are special kind of Urls, which you can add to your next.js application, which are not about getting a standard browser request and sending back a prerendered html page, but which are about getting data, using data maybe storing data in some database and sending back data in any form of your choice.


问:
When is it the right time to use C# class library (.dll)?
I'm a programmer who has never really used .dll files.
Of cause, when I need 3rd party software, such as a graphics library, a library to help me create graphs etc. I do add the references/ddl files to my program and use them in my code.

Also, it seems like you can use .dll for a lot of different things, so I'd like the topic to concentrate on C#.

Right now I am working on a sanitizing library(?) (I think that is the correct term), which will be full of relevant methods that can sanitize variables in all sorts of different ways.

What I want to know is:

would there be any advantage to:

1) Write the methods to class library -> compile/build it -> add the library as a reference to the program - which would need to sanitize some variables ?

Or would it be exactly the same if I where to:

2) Create a new SanitizeClass in the program -> add all the sanitize methods -> call the methods from the SanitizeClass in the different classes in the program that needs to sanitize variables

In general, I also want to know when it is an advantage to use compiled class libraries.
I'm thinking of speed, security, all of it.

Could anyone enlightenment me? :)

答: The first thought that comes to mind is re usability. Will this sanitize library be used ever outside of the application you're currently working on? If you are, then you don't want to have to reference an exe in the future, for that you want to build a DLL file (possibly even strong name it and GAC it) and then just reference that in the future.</p>

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: BFree


问:
jQuery upload plugin to work with JSP/Java
I'm trying to accomplish the following:

Upload a file to the application by submitting a form (enctype: multipart/form-data) to a JSP action which handles the rest (including writing the file to the disk, processing and returning some xml data about the upload).

Until recently, I was using this plugin:
http://valums.com/ajax-upload/

This does not work well for two reasons:

it breaks on Internet Explorer

the code is written in half jquery, half native javascript and not in your usual plugin authoring form, which makes it harder to debug.

I've also looked at Uploadify ( http://www.uploadify.com/ ) but it takes a radically different approach which would require a lot of back-end changes.

Do you know any similar submit-form-in-hidden-iframe plugins that are cleaner / cross-browser compatible? Or alternative solutions that I'm missing?

Please note that I can't use a regular  because of the specific requirements.

Thanks.

答: You may try: plupload. It's back-end independent, and cross-browser.</p>


问:
how to return values from a Laravel Sever to React with inertiajs?
I'm am trying to get a message to show after a post in React from a Laraval server using InertiaJS.

From what I can find in docs / online / in other (semi) related questions the following is an isolated version of what I think should work - I'm under the impression it should be added to my props. My Test component does reload so the redirect is working just with no message and props remaining undefined - What am I not understanding?

Laravel Controller:

```<code>use Illuminate\Support\Facades\Redirect;
use Inertia\Inertia;
use Illuminate\Routing\Controller as BaseController;

class TestController extends BaseController
{
    function test(){
       return Inertia::render('Test');
    }

    function testResponse(){
        //dd("I GET TO HERE, SO ITS NOT A ROUTING ISSUE!")
        return Redirect::back()->with('message', 'Test message from server.');
    }
}
</code>```

My React Test Component

```<code>import { Link } from '@inertiajs/inertia-react';
import React from 'react';

const Test = (props) => {

    const [serverMessage, setServerMessage] = useState('no message');

  return <div>
      <div>{serverMessage}</div>
      <Link className="hover:bg-blue-700 bg-blue-400 text-white py-1 px-3 rounded" href={route('testResponse')} method="post" as="button">
          Get Server Response
      </Link>
  </div>;
};

export default Test;
</code>```

答:
It is because the flash message is not passed to the react component. To do that, you need to modify the HandleInertiaRequest.php to add a props for flash message that is globally accessible. That means the props is for all the pages.

```<code>public function share(Request $request)
{
    return array_merge(parent::share($request), [
        'auth' => [
            'user' => $request->user(),
        ],
        'flash' => [
            'message' => fn () => $request->session()->get('message'),
        ],
    ]);
}
</code>```

Then, in /resource/js/pages/Test.jsx, you will have the following code

```<code>import { Link } from '@inertiajs/inertia-react'
import React, { useEffect, useState } from 'react'

const Test = (props) => {
    const [serverMessage, setServerMessage] = useState('no message')

    console.log('Test.jsx props: ', props)

    useEffect(() => {
        const {
            flash: { message = '' },
        } = props
        if (message) {
            setServerMessage(message)
        }
    }, [props.flash.message])

    return (
        <div>
            <div>{serverMessage}</div>
            <Link
                className='hover:bg-blue-700 bg-blue-400 text-white py-1 px-3 rounded'
                href={route('testResponse')}
                method='post'
                as='button'
            >
                Get Server Response
            </Link>
        </div>
    )
}

export default Test

</code>```

Btw you're missing the useState import at the top.

And then in web.php you should define the routes like this:

```<code>use App\Http\Controllers\TestController;

Route::get('/test', [TestController::class, 'test'])->name('test');
Route::post('/testResponse', [TestController::class, 'testResponse'])->name('testResponse');
</code>```

Actually this is documented in the inertia js. Check out https://inertiajs.com/shared-data

Body:
I'm am trying to get a message to show after a post in React from a Laraval server using InertiaJS.

From what I can find in docs / online / in other (semi) related questions the following is an isolated version of what I think should work - I'm under the impression it should be added to my props. My Test component does reload so the redirect is working just with no message and props remaining undefined - What am I not understanding?

Laravel Controller:

use Illuminate\Support\Facades\Redirect;
use Inertia\Inertia;
use Illuminate\Routing\Controller as BaseController;

class TestController extends BaseController
{
    function test(){
       return Inertia::render('Test');
    }

    function testResponse(){
        //dd("I GET TO HERE, SO ITS NOT A ROUTING ISSUE!")
        return Redirect::back()->with('message', 'Test message from server.');
    }
}

My React Test Component

import { Link } from '@inertiajs/inertia-react';
import React from 'react';

const Test = (props) => {

    const [serverMessage, setServerMessage] = useState('no message');

  return

{serverMessage}

      <Link className="hover:bg-blue-700 bg-blue-400 text-white py-1 px-3 rounded" href={route('testResponse')} method="post" as="button">
          Get Server Response
      </Link>

;
};

export default Test;

Body:
It is because the flash message is not passed to the react component. To do that, you need to modify the HandleInertiaRequest.php to add a props for flash message that is globally accessible. That means the props is for all the pages.

public function share(Request $request)
{
    return array_merge(parent::share($request), [
        'auth' => [
            'user' => $request->user(),
        ],
        'flash' => [
            'message' => fn () => $request->session()->get('message'),
        ],
    ]);
}

Then, in /resource/js/pages/Test.jsx, you will have the following code

import { Link } from '@inertiajs/inertia-react'
import React, { useEffect, useState } from 'react'

const Test = (props) => {
    const [serverMessage, setServerMessage] = useState('no message')

    console.log('Test.jsx props: ', props)

    useEffect(() => {
        const {
            flash: { message = '' },
        } = props
        if (message) {
            setServerMessage(message)
        }
    }, [props.flash.message])

    return (
        <div>
            <div>{serverMessage}</div>
            <Link
                className='hover:bg-blue-700 bg-blue-400 text-white py-1 px-3 rounded'
                href={route('testResponse')}
                method='post'
                as='button'
            >
                Get Server Response
            </Link>
        </div>
    )
}

export default Test

Btw you're missing the useState import at the top.

And then in web.php you should define the routes like this:

use App\Http\Controllers\TestController;

Route::get('/test', [TestController::class, 'test'])->name('test');
Route::post('/testResponse', [TestController::class, 'testResponse'])->name('testResponse');

Actually this is documented in the inertia js. Check out https://inertiajs.com/shared-data


问:
How do I get both the sum and an overlapping a list of dates that fall within a sliding window in a Pandas df?
I have a df like this:

date
name
amount

2021-07-01
'Chlorox'
1

2021-07-14
'Chlorox'
20

2021-07-29
'Chlorox'
700

2021-08-11
'Chlorox'
6000

2021-08-12
'Suriname'
3

2021-08-19
'Suriname'
10

and I'd like the sum of amounts within a one month period, (So 7-20 and 8-11 would be within the same period), plus all the dates that fall within that month range. So something like these results:

name
sum
dates

'Chlorox'
721
['2021-07-01', '2021-07-14', '2021-07-29']

'Chlorox'
6720
'2021-07-14', '2021-07-29', '2021-08-11'

'Suriname'
13
['2021-08-12', '2021-08-19']

I've been tinkering around with rolling() and groupby, but I've been struggling and unable to get overlapping dates!

答:
Use pd.to_datetime, Series.dt.to_period with Groupby.agg:

```<code>In [874]: df['date'] = pd.to_datetime(df['date']) # Convert date column to pandas datetime

In [923]: res = df.groupby(['name', df['date'].dt.to_period('M')], as_index=False).agg({'amount': sum, 'date': lambda x: list(x.dt.date)})

In [924]: res
Out[924]:
         name  amount                                  date
0   'Chlorox'     721  [2021-07-01, 2021-07-14, 2021-07-29]
1   'Chlorox'    6000                          [2021-08-11]
2  'Suriname'      13              [2021-08-12, 2021-08-19]
</code>```

Body:
Use pd.to_datetime, Series.dt.to_period with Groupby.agg:

In [874]: df['date'] = pd.to_datetime(df['date']) # Convert date column to pandas datetime

In [923]: res = df.groupby(['name', df['date'].dt.to_period('M')], as_index=False).agg({'amount': sum, 'date': lambda x: list(x.dt.date)})

In [924]: res
Out[924]:
         name  amount                                  date
0   'Chlorox'     721  [2021-07-01, 2021-07-14, 2021-07-29]
1   'Chlorox'    6000                          [2021-08-11]
2  'Suriname'      13              [2021-08-12, 2021-08-19]


问:
ggplot2 grouped bar chart for months over several years is producing overlapping bars
I am trying to make a grouped bar chart and the bars are crowded and overlapping for my x-values. How do I get the grouped bar chart to plot correctly?

I've tried formatting the date with as.yearmon to sort the table for graphing; I have also formatted the table with year and month in separate columns for ease of graphing. However, neither format has worked for me. I have tried as.date and lubridate also and have had no luck so far.

Here is what my data frame looks like:

```<code>structure(list(Month = c("August", "July", "June", "May", "November",
"October", "September", "April", "August", "December", "February",
"July", "June", "March", "May", "November", "October", "September",
"April", "August", "December", "February", "January", "July",
"June", "March", "May", "November", "October", "September", "April",
"August", "February", "January", "July", "June", "March", "May",
"November", "October", "September", "January", "August", "July",
"June", "May", "November", "October", "September", "April", "August",
"December", "July", "June", "March", "May", "November", "October",
"September", "April", "August", "December", "February", "January",
"July", "June", "March", "May", "November", "October", "September",
"April", "August", "February", "January", "July", "June", "March",
"May", "November", "October", "September", "January", "August",
"July", "June", "May", "November", "October", "September", "April",
"August", "December", "February", "July", "June", "March", "May",
"November", "October", "September", "April", "August", "December",
"February", "January", "July", "June", "March", "May", "November",
"October", "September", "April", "August", "February", "January",
"July", "June", "March", "May", "November", "October", "September",
"January"), Year = c(2016L, 2016L, 2016L, 2016L, 2016L, 2016L,
2016L, 2017L, 2017L, 2017L, 2017L, 2017L, 2017L, 2017L, 2017L,
2017L, 2017L, 2017L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L,
2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2019L, 2019L, 2019L,
2019L, 2019L, 2019L, 2019L, 2019L, 2019L, 2019L, 2019L, 2020L,
2016L, 2016L, 2016L, 2016L, 2016L, 2016L, 2016L, 2017L, 2017L,
2017L, 2017L, 2017L, 2017L, 2017L, 2017L, 2017L, 2017L, 2018L,
2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L,
2018L, 2018L, 2019L, 2019L, 2019L, 2019L, 2019L, 2019L, 2019L,
2019L, 2019L, 2019L, 2019L, 2020L, 2016L, 2016L, 2016L, 2016L,
2016L, 2016L, 2016L, 2017L, 2017L, 2017L, 2017L, 2017L, 2017L,
2017L, 2017L, 2017L, 2017L, 2017L, 2018L, 2018L, 2018L, 2018L,
2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2019L,
2019L, 2019L, 2019L, 2019L, 2019L, 2019L, 2019L, 2019L, 2019L,
2019L, 2020L), DSG.Station = structure(c(2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("9M", "14M", "37M"
), class = "factor"), Richness = c(3.75, 3, 11.5, 6.16666666666667,
0, 0, 1.5, 4.25, 5.75, 3.5, 0, 8, 9.5, 2.6, 7.75, 5.25, 9.16666666666667,
6.25, 6.5, 10, 7, 4, 3.5, 8, 11, 5.75, 7, 7.66666666666667, 5.66666666666667,
8.33333333333333, 7, 6, 4.5, 3.5, 10, 5.5, 8.5, 10.5, 2, 5.5,
12.5, 5, 5, 5.5, 6, 5.66666666666667, 0.5, 1.5, 2, 4.5, 9, 5.16666666666667,
5.66666666666667, 7, 0.5, 8, 7.25, 6.5, 5, 6.5, 6, 5, 4.75, 3.25,
7.5, 10, 6.5, 8.25, 7, 8, 6.66666666666667, 11, 10.5, 9.5, 5,
7.5, 6.5, 4.5, 10, 4.5, 3.5, 8.5, 3, 4, 4.5, 9, 10, 1.8, 3.25,
1, 5.5, 6, 3.5, 1, 7, 5, 2.5, 6.66666666666667, 3.75, 5.5, 6.5,
7, 9.5, 4, 6.25, 3.5, 8.5, 11.3333333333333, 6.75, 6.5, 5, 8.66666666666667,
7.33333333333333, 9, 9, 4.5, 3, 9, 13.5, 6.5, 9, 3.5, 3, 11,
6.5), yrmn = c("2016 August", "2016 July", "2016 June", "2016 May",
"2016 November", "2016 October", "2016 September", "2017 April",
"2017 August", "2017 December", "2017 February", "2017 July",
"2017 June", "2017 March", "2017 May", "2017 November", "2017 October",
"2017 September", "2018 April", "2018 August", "2018 December",
"2018 February", "2018 January", "2018 July", "2018 June", "2018 March",
"2018 May", "2018 November", "2018 October", "2018 September",
"2019 April", "2019 August", "2019 February", "2019 January",
"2019 July", "2019 June", "2019 March", "2019 May", "2019 November",
"2019 October", "2019 September", "2020 January", "2016 August",
"2016 July", "2016 June", "2016 May", "2016 November", "2016 October",
"2016 September", "2017 April", "2017 August", "2017 December",
"2017 July", "2017 June", "2017 March", "2017 May", "2017 November",
"2017 October", "2017 September", "2018 April", "2018 August",
"2018 December", "2018 February", "2018 January", "2018 July",
"2018 June", "2018 March", "2018 May", "2018 November", "2018 October",
"2018 September", "2019 April", "2019 August", "2019 February",
"2019 January", "2019 July", "2019 June", "2019 March", "2019 May",
"2019 November", "2019 October", "2019 September", "2020 January",
"2016 August", "2016 July", "2016 June", "2016 May", "2016 November",
"2016 October", "2016 September", "2017 April", "2017 August",
"2017 December", "2017 February", "2017 July", "2017 June", "2017 March",
"2017 May", "2017 November", "2017 October", "2017 September",
"2018 April", "2018 August", "2018 December", "2018 February",
"2018 January", "2018 July", "2018 June", "2018 March", "2018 May",
"2018 November", "2018 October", "2018 September", "2019 April",
"2019 August", "2019 February", "2019 January", "2019 July",
"2019 June", "2019 March", "2019 May", "2019 November", "2019 October",
"2019 September", "2020 January")), row.names = c(NA, -125L), class = "data.frame")
</code>```

Here is my code for the plot:

```<code>ggplot(rich.mean2, aes(factor(DSG.Station), fill=DSG.Station, y=Richness, x=yrmn)) +
  geom_bar (position = position_dodge(2.5), width= 2, colour= 'black', stat='identity')+
  ggtitle('Richness Per Month')+
  theme(axis.text = element_text(size=7, colour =  'black'), panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
        panel.background = element_blank(), axis.line = element_line(colour = "black" ))+
  scale_y_continuous(expand = c(0,0))+
  scale_x_discrete(limits=rich.mean2$yrmn)
</code>```

You can see how the plot is very overlapping. The error I am getting is:

```<code>Warning message: position_dodge requires non-overlapping x intervals
</code>```

答:
To plot the data in the correct order, we can transform the months into a factor using month.name (built into base R). Then, we can arrange by Year and Month, and combine them into one column, yrmn. Now that they are in order, we can set the order with factor. Now, we can plot as normal, but can set the spacing between groups to width = 0.7 and increase spacing between bars with position_dodge, where we can specify the distance between bars. Note: You cannot increase the normal width parameter too much when using  position_dodge as it will push the bars into the other x-intervals, which is the reason for the warning message (i.e., position_dodge requires non-overlapping x intervals).

```<code>library(tidyverse)

rich.mean2 %>%
  mutate(Month = factor(Month, levels = month.name)) %>%
  arrange(Year, Month) %>%
  unite(yrmn, c(Month:Year), sep = " ") %>%
  mutate(yrmn = factor(yrmn, levels = unique(yrmn))) %>%
  ggplot(., aes(x = yrmn, y = Richness, fill = DSG.Station)) +
  geom_bar(stat = "identity",
           width = 0.7,
           position = position_dodge(width = 0.8)) +
  theme(axis.text.x = element_text(
    angle = 90,
    vjust = 0.5,
    hjust = 1
  )) +
  ggtitle('Richness Per Month') +
  theme(
    axis.text = element_text(size = 7, colour =  'black'),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.background = element_blank(),
    axis.line = element_line(colour = "black"),
    axis.text.x = element_text(
      angle = 90,
      vjust = 0.5,
      hjust = 1
    )
  ) +
  scale_y_continuous(expand = c(0, 0))
</code>```

Output

Update 1

For filling in missing months, we can use base R month.name within complete from tidyr. Next, I convert the month name to a number and add the leading 0, which is needed for the date format. Next, I combine Year, Month, and day (i.e., "01"). Then, I arrange by yrmn. Then, I convert to just show month-year. Then, if you want to go back to names rather than month numbers, then we can convert it back. However, if you are fine with date numbers (i.e., 09-2016), then you can comment out the line with separate and the 2 subsequent lines (i.e., through unite). So, now you will see, gaps where there is no data for a given month.

```<code>df %>%
  complete(Month = month.name, nesting(Year), fill = list(Richness = NA, DSG.Station = NA)) %>%
  mutate(Month = formatC(match(Month, month.name), width = 2, format = "d", flag = "0")) %>%
  mutate(yrmn = paste(Year, Month, "01", sep="-")) %>%
  arrange(yrmn) %>%
  mutate(yrmn = format(as.Date(yrmn, format="%Y-%m-%d"), "%m-%Y")) %>%
  separate(yrmn, c("Month", "Year"), sep = "-") %>%
  mutate(Month = with(., month.abb[as.integer(str_remove(Month, "^0+"))])) %>%
  unite("yrmn", c(Month, Year), sep = " ") %>%
  mutate(yrmn = factor(yrmn, levels = unique(yrmn))) %>%
  ggplot(., aes(x = yrmn, y = Richness, fill = DSG.Station)) +
  geom_bar(stat = "identity",
           width = 0.7,
           position = position_dodge(width = 0.8)) +
  theme(axis.text.x = element_text(
    angle = 90,
    vjust = 0.5,
    hjust = 1
  )) +
  ggtitle('Richness Per Month') +
  theme(
    axis.text = element_text(size = 7, colour =  'black'),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.background = element_blank(),
    axis.line = element_line(colour = "black"),
    axis.text.x = element_text(
      angle = 90,
      vjust = 0.5,
      hjust = 1
    )
  ) +
  scale_y_continuous(expand = c(0, 0))
</code>```

Output

Update 2

If you want to remove the first NAs until you reach a value, then we can use a combination of complete.cases and cumsum, then we can also do the same thing in reverse for the end of the dataframe.

```<code>df %>%
  complete(Month = month.name, nesting(Year), fill = list(Richness = NA, DSG.Station = NA)) %>%
  mutate(Month = formatC(match(Month, month.name), width = 2, format = "d", flag = "0"),
         yrmn = paste(Year, Month, "01", sep="-")) %>%
  arrange(yrmn) %>%
  mutate(yrmn = format(as.Date(yrmn, format="%Y-%m-%d"), "%m-%Y")) %>%
  separate(yrmn, c("Month", "Year"), sep = "-") %>%
  mutate(Month = with(., month.abb[as.integer(str_remove(Month, "^0+"))])) %>%
  unite("yrmn", c(Month, Year), sep = " ") %>%
  filter(cumsum(complete.cases(.)) != 0 & rev(cumsum(rev(complete.cases(.)))) != 0) %>%
  mutate(yrmn = factor(yrmn, levels = unique(yrmn))) %>%
  ggplot(., aes(x = yrmn, y = Richness, fill = DSG.Station)) +
  geom_bar(stat = "identity",
           width = 0.7,
           position = position_dodge(width = 0.8)) +
  theme(axis.text.x = element_text(
    angle = 90,
    vjust = 0.5,
    hjust = 1
  )) +
  ggtitle('Richness Per Month') +
  theme(
    axis.text = element_text(size = 7, colour =  'black'),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.background = element_blank(),
    axis.line = element_line(colour = "black"),
    axis.text.x = element_text(
      angle = 90,
      vjust = 0.5,
      hjust = 1
    )
  ) +
  scale_y_continuous(expand = c(0, 0))
</code>```

Output

Body:
I am trying to make a grouped bar chart and the bars are crowded and overlapping for my x-values. How do I get the grouped bar chart to plot correctly?

I've tried formatting the date with as.yearmon to sort the table for graphing; I have also formatted the table with year and month in separate columns for ease of graphing. However, neither format has worked for me. I have tried as.date and lubridate also and have had no luck so far.

Here is what my data frame looks like:

structure(list(Month = c("August", "July", "June", "May", "November",
"October", "September", "April", "August", "December", "February",
"July", "June", "March", "May", "November", "October", "September",
"April", "August", "December", "February", "January", "July",
"June", "March", "May", "November", "October", "September", "April",
"August", "February", "January", "July", "June", "March", "May",
"November", "October", "September", "January", "August", "July",
"June", "May", "November", "October", "September", "April", "August",
"December", "July", "June", "March", "May", "November", "October",
"September", "April", "August", "December", "February", "January",
"July", "June", "March", "May", "November", "October", "September",
"April", "August", "February", "January", "July", "June", "March",
"May", "November", "October", "September", "January", "August",
"July", "June", "May", "November", "October", "September", "April",
"August", "December", "February", "July", "June", "March", "May",
"November", "October", "September", "April", "August", "December",
"February", "January", "July", "June", "March", "May", "November",
"October", "September", "April", "August", "February", "January",
"July", "June", "March", "May", "November", "October", "September",
"January"), Year = c(2016L, 2016L, 2016L, 2016L, 2016L, 2016L,
2016L, 2017L, 2017L, 2017L, 2017L, 2017L, 2017L, 2017L, 2017L,
2017L, 2017L, 2017L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L,
2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2019L, 2019L, 2019L,
2019L, 2019L, 2019L, 2019L, 2019L, 2019L, 2019L, 2019L, 2020L,
2016L, 2016L, 2016L, 2016L, 2016L, 2016L, 2016L, 2017L, 2017L,
2017L, 2017L, 2017L, 2017L, 2017L, 2017L, 2017L, 2017L, 2018L,
2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L,
2018L, 2018L, 2019L, 2019L, 2019L, 2019L, 2019L, 2019L, 2019L,
2019L, 2019L, 2019L, 2019L, 2020L, 2016L, 2016L, 2016L, 2016L,
2016L, 2016L, 2016L, 2017L, 2017L, 2017L, 2017L, 2017L, 2017L,
2017L, 2017L, 2017L, 2017L, 2017L, 2018L, 2018L, 2018L, 2018L,
2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2019L,
2019L, 2019L, 2019L, 2019L, 2019L, 2019L, 2019L, 2019L, 2019L,
2019L, 2020L), DSG.Station = structure(c(2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("9M", "14M", "37M"
), class = "factor"), Richness = c(3.75, 3, 11.5, 6.16666666666667,
0, 0, 1.5, 4.25, 5.75, 3.5, 0, 8, 9.5, 2.6, 7.75, 5.25, 9.16666666666667,
6.25, 6.5, 10, 7, 4, 3.5, 8, 11, 5.75, 7, 7.66666666666667, 5.66666666666667,
8.33333333333333, 7, 6, 4.5, 3.5, 10, 5.5, 8.5, 10.5, 2, 5.5,
12.5, 5, 5, 5.5, 6, 5.66666666666667, 0.5, 1.5, 2, 4.5, 9, 5.16666666666667,
5.66666666666667, 7, 0.5, 8, 7.25, 6.5, 5, 6.5, 6, 5, 4.75, 3.25,
7.5, 10, 6.5, 8.25, 7, 8, 6.66666666666667, 11, 10.5, 9.5, 5,
7.5, 6.5, 4.5, 10, 4.5, 3.5, 8.5, 3, 4, 4.5, 9, 10, 1.8, 3.25,
1, 5.5, 6, 3.5, 1, 7, 5, 2.5, 6.66666666666667, 3.75, 5.5, 6.5,
7, 9.5, 4, 6.25, 3.5, 8.5, 11.3333333333333, 6.75, 6.5, 5, 8.66666666666667,
7.33333333333333, 9, 9, 4.5, 3, 9, 13.5, 6.5, 9, 3.5, 3, 11,
6.5), yrmn = c("2016 August", "2016 July", "2016 June", "2016 May",
"2016 November", "2016 October", "2016 September", "2017 April",
"2017 August", "2017 December", "2017 February", "2017 July",
"2017 June", "2017 March", "2017 May", "2017 November", "2017 October",
"2017 September", "2018 April", "2018 August", "2018 December",
"2018 February", "2018 January", "2018 July", "2018 June", "2018 March",
"2018 May", "2018 November", "2018 October", "2018 September",
"2019 April", "2019 August", "2019 February", "2019 January",
"2019 July", "2019 June", "2019 March", "2019 May", "2019 November",
"2019 October", "2019 September", "2020 January", "2016 August",
"2016 July", "2016 June", "2016 May", "2016 November", "2016 October",
"2016 September", "2017 April", "2017 August", "2017 December",
"2017 July", "2017 June", "2017 March", "2017 May", "2017 November",
"2017 October", "2017 September", "2018 April", "2018 August",
"2018 December", "2018 February", "2018 January", "2018 July",
"2018 June", "2018 March", "2018 May", "2018 November", "2018 October",
"2018 September", "2019 April", "2019 August", "2019 February",
"2019 January", "2019 July", "2019 June", "2019 March", "2019 May",
"2019 November", "2019 October", "2019 September", "2020 January",
"2016 August", "2016 July", "2016 June", "2016 May", "2016 November",
"2016 October", "2016 September", "2017 April", "2017 August",
"2017 December", "2017 February", "2017 July", "2017 June", "2017 March",
"2017 May", "2017 November", "2017 October", "2017 September",
"2018 April", "2018 August", "2018 December", "2018 February",
"2018 January", "2018 July", "2018 June", "2018 March", "2018 May",
"2018 November", "2018 October", "2018 September", "2019 April",
"2019 August", "2019 February", "2019 January", "2019 July",
"2019 June", "2019 March", "2019 May", "2019 November", "2019 October",
"2019 September", "2020 January")), row.names = c(NA, -125L), class = "data.frame")

Here is my code for the plot:

ggplot(rich.mean2, aes(factor(DSG.Station), fill=DSG.Station, y=Richness, x=yrmn)) +
  geom_bar (position = position_dodge(2.5), width= 2, colour= 'black', stat='identity')+
  ggtitle('Richness Per Month')+
  theme(axis.text = element_text(size=7, colour =  'black'), panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
        panel.background = element_blank(), axis.line = element_line(colour = "black" ))+
  scale_y_continuous(expand = c(0,0))+
  scale_x_discrete(limits=rich.mean2$yrmn)

You can see how the plot is very overlapping. The error I am getting is:

Warning message: position_dodge requires non-overlapping x intervals

Body:
To plot the data in the correct order, we can transform the months into a factor using month.name (built into base R). Then, we can arrange by Year and Month, and combine them into one column, yrmn. Now that they are in order, we can set the order with factor. Now, we can plot as normal, but can set the spacing between groups to width = 0.7 and increase spacing between bars with position_dodge, where we can specify the distance between bars. Note: You cannot increase the normal width parameter too much when using  position_dodge as it will push the bars into the other x-intervals, which is the reason for the warning message (i.e., position_dodge requires non-overlapping x intervals).

library(tidyverse)

rich.mean2 %>%
  mutate(Month = factor(Month, levels = month.name)) %>%
  arrange(Year, Month) %>%
  unite(yrmn, c(Month:Year), sep = " ") %>%
  mutate(yrmn = factor(yrmn, levels = unique(yrmn))) %>%
  ggplot(., aes(x = yrmn, y = Richness, fill = DSG.Station)) +
  geom_bar(stat = "identity",
           width = 0.7,
           position = position_dodge(width = 0.8)) +
  theme(axis.text.x = element_text(
    angle = 90,
    vjust = 0.5,
    hjust = 1
  )) +
  ggtitle('Richness Per Month') +
  theme(
    axis.text = element_text(size = 7, colour =  'black'),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.background = element_blank(),
    axis.line = element_line(colour = "black"),
    axis.text.x = element_text(
      angle = 90,
      vjust = 0.5,
      hjust = 1
    )
  ) +
  scale_y_continuous(expand = c(0, 0))

Output

Update 1

For filling in missing months, we can use base R month.name within complete from tidyr. Next, I convert the month name to a number and add the leading 0, which is needed for the date format. Next, I combine Year, Month, and day (i.e., "01"). Then, I arrange by yrmn. Then, I convert to just show month-year. Then, if you want to go back to names rather than month numbers, then we can convert it back. However, if you are fine with date numbers (i.e., 09-2016), then you can comment out the line with separate and the 2 subsequent lines (i.e., through unite). So, now you will see, gaps where there is no data for a given month.

df %>%
  complete(Month = month.name, nesting(Year), fill = list(Richness = NA, DSG.Station = NA)) %>%
  mutate(Month = formatC(match(Month, month.name), width = 2, format = "d", flag = "0")) %>%
  mutate(yrmn = paste(Year, Month, "01", sep="-")) %>%
  arrange(yrmn) %>%
  mutate(yrmn = format(as.Date(yrmn, format="%Y-%m-%d"), "%m-%Y")) %>%
  separate(yrmn, c("Month", "Year"), sep = "-") %>%
  mutate(Month = with(., month.abb[as.integer(str_remove(Month, "^0+"))])) %>%
  unite("yrmn", c(Month, Year), sep = " ") %>%
  mutate(yrmn = factor(yrmn, levels = unique(yrmn))) %>%
  ggplot(., aes(x = yrmn, y = Richness, fill = DSG.Station)) +
  geom_bar(stat = "identity",
           width = 0.7,
           position = position_dodge(width = 0.8)) +
  theme(axis.text.x = element_text(
    angle = 90,
    vjust = 0.5,
    hjust = 1
  )) +
  ggtitle('Richness Per Month') +
  theme(
    axis.text = element_text(size = 7, colour =  'black'),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.background = element_blank(),
    axis.line = element_line(colour = "black"),
    axis.text.x = element_text(
      angle = 90,
      vjust = 0.5,
      hjust = 1
    )
  ) +
  scale_y_continuous(expand = c(0, 0))

Output

Update 2

If you want to remove the first NAs until you reach a value, then we can use a combination of complete.cases and cumsum, then we can also do the same thing in reverse for the end of the dataframe.

df %>%
  complete(Month = month.name, nesting(Year), fill = list(Richness = NA, DSG.Station = NA)) %>%
  mutate(Month = formatC(match(Month, month.name), width = 2, format = "d", flag = "0"),
         yrmn = paste(Year, Month, "01", sep="-")) %>%
  arrange(yrmn) %>%
  mutate(yrmn = format(as.Date(yrmn, format="%Y-%m-%d"), "%m-%Y")) %>%
  separate(yrmn, c("Month", "Year"), sep = "-") %>%
  mutate(Month = with(., month.abb[as.integer(str_remove(Month, "^0+"))])) %>%
  unite("yrmn", c(Month, Year), sep = " ") %>%
  filter(cumsum(complete.cases(.)) != 0 & rev(cumsum(rev(complete.cases(.)))) != 0) %>%
  mutate(yrmn = factor(yrmn, levels = unique(yrmn))) %>%
  ggplot(., aes(x = yrmn, y = Richness, fill = DSG.Station)) +
  geom_bar(stat = "identity",
           width = 0.7,
           position = position_dodge(width = 0.8)) +
  theme(axis.text.x = element_text(
    angle = 90,
    vjust = 0.5,
    hjust = 1
  )) +
  ggtitle('Richness Per Month') +
  theme(
    axis.text = element_text(size = 7, colour =  'black'),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.background = element_blank(),
    axis.line = element_line(colour = "black"),
    axis.text.x = element_text(
      angle = 90,
      vjust = 0.5,
      hjust = 1
    )
  ) +
  scale_y_continuous(expand = c(0, 0))

Output


问:
remove const qualifier of vector in c++
Is it possible to remove constness of vector ? If so, how can it be achieved? For some reason, I don't have access to the main (), can I still remove the constness of arr in the following code snipet? It feels like that auto arr0 = const_cast<vector<int> & > (arr); is identical to vector<int> arr0 = arr;. I guess it is just an example of explicit vs implicit cast,which both creates a copy of original array ````arr```. Is it possible to remove constness inplace without creating a copy?

```<code>#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

vector<int> func(const vector<int>& arr){
//    vector<int> arr0 = arr;
    auto arr0 = const_cast<vector<int> & > (arr);
    sort(arr0.begin(), arr0.end());
    return arr0;
}

int main(){
    const vector<int> arr = {3,4,1,5,2};
    auto res = func(arr);
    for (auto n:res)
        cout<<n<<" ";
    return 0;

}
</code>```

答:
Don't attempt to cast away constness. Modifing a const object will result in undefined behaviour.

It feels like that auto arr0 = const_cast<vector<int> & > (arr); is identical to vector<int> arr0 = arr;

It is effectively the same. The cast is redundant.

Is it possible to remove constness inplace without creating a copy?

If you wish to sort a vector without making a copy, then don't make the vector const in the first place. If it is const, then you cannot modify it.

then what is the point of have const_cast in c++?

It's rarely needed, but there are a few use cases.

You can use it to convert a non-const glvalue expression into a const one:

```<code>void fun(T&);       // overload 1
void fun(const T&); // overload 2
T t;
fun(t);                       // calls 1
fun(const_cast<const T&>(t)); // calls 2
</code>```

If you have a provably non-const object, and a const reference referring to the non-const object, then you can cast away constness of the reference:

```<code>T t;
const T& ref = t;
const_cast<T&>(ref) = new_value;
</code>```

Same cases apply to volatile qualifier, although that's even more rarely needed.

Title: remove const qualifier of vector in c++

Body:
Is it possible to remove constness of vector ? If so, how can it be achieved? For some reason, I don't have access to the main (), can I still remove the constness of arr in the following code snipet? It feels like that auto arr0 = const_cast<vector<int> & > (arr); is identical to vector<int> arr0 = arr;. I guess it is just an example of explicit vs implicit cast,which both creates a copy of original array ````arr```. Is it possible to remove constness inplace without creating a copy?

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

vector<int> func(const vector<int>& arr){
//    vector<int> arr0 = arr;
    auto arr0 = const_cast<vector<int> & > (arr);
    sort(arr0.begin(), arr0.end());
    return arr0;
}

int main(){
    const vector<int> arr = {3,4,1,5,2};
    auto res = func(arr);
    for (auto n:res)
        cout<<n<<" ";
    return 0;

}

Body:
Don't attempt to cast away constness. Modifing a const object will result in undefined behaviour.

It feels like that auto arr0 = const_cast<vector<int> & > (arr); is identical to vector<int> arr0 = arr;

It is effectively the same. The cast is redundant.

Is it possible to remove constness inplace without creating a copy?

If you wish to sort a vector without making a copy, then don't make the vector const in the first place. If it is const, then you cannot modify it.

then what is the point of have const_cast in c++?

It's rarely needed, but there are a few use cases.

You can use it to convert a non-const glvalue expression into a const one:

void fun(T&);       // overload 1
void fun(const T&); // overload 2
T t;
fun(t);                       // calls 1
fun(const_cast<const T&>(t)); // calls 2

If you have a provably non-const object, and a const reference referring to the non-const object, then you can cast away constness of the reference:

T t;
const T& ref = t;
const_cast<T&>(ref) = new_value;

Same cases apply to volatile qualifier, although that's even more rarely needed.


问:
API binance P2P I only access a part (only the BUY) and not all of it (BUY and SELL)
I am trying to access the data on this Binance website. It is the P2P: https://p2p.binance.com/en/trade/buy/USDT.

For BUY I am using this in python3 (I am getting the data correctly for this section):

import requests

headers = {
    "Accept": "*/*",
    "Accept-Encoding": "gzip, deflate, br",
    "Accept-Language": "en-GB,en-US;q=0.9,en;q=0.8",
    "Cache-Control": "no-cache",
    "Connection": "keep-alive",
    "Content-Length": "123",
    "content-type": "application/json",
    "Host": "p2p.binance.com",
    "Origin": "https://p2p.binance.com",
    "Pragma": "no-cache",
    "TE": "Trailers",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0"
}

data = {
  "asset": "USDT",
  "fiat": "ARS",
  "merchantCheck": False,
  "page": 1,
  "payTypes": [],
  "publisherType": None,
  "rows": 50,
  "tradeType": "BUY"
}

r = requests.post('https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search', headers=headers, json=data)
print(r.text)

```

But then when I want to access this part of the page: https://p2p.binance.com/en/trade/sell/USDT (to SELL), I can't do it. Because when I change in the data the following: "tradeType": "SELL", it still brings me the same values of the BUY. It never brings me the SELL data.

And I am not finding out why yet.

答:
You need use it:

client.get_c2c_trade_history() and go to ['data']
Next step is work like json or dateframe, the column that you need have the header 'tradeType'

Body:
I am trying to access the data on this Binance website. It is the P2P: https://p2p.binance.com/en/trade/buy/USDT.

For BUY I am using this in python3 (I am getting the data correctly for this section):

import requests

headers = {
    "Accept": "*/*",
    "Accept-Encoding": "gzip, deflate, br",
    "Accept-Language": "en-GB,en-US;q=0.9,en;q=0.8",
    "Cache-Control": "no-cache",
    "Connection": "keep-alive",
    "Content-Length": "123",
    "content-type": "application/json",
    "Host": "p2p.binance.com",
    "Origin": "https://p2p.binance.com",
    "Pragma": "no-cache",
    "TE": "Trailers",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0"
}

data = {
  "asset": "USDT",
  "fiat": "ARS",
  "merchantCheck": False,
  "page": 1,
  "payTypes": [],
  "publisherType": None,
  "rows": 50,
  "tradeType": "BUY"
}

r = requests.post('https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search', headers=headers, json=data)
print(r.text)

But then when I want to access this part of the page: https://p2p.binance.com/en/trade/sell/USDT (to SELL), I can't do it. Because when I change in the data the following: "tradeType": "SELL", it still brings me the same values of the BUY. It never brings me the SELL data.

And I am not finding out why yet.


问:
How to use Python to edit the text value of a line of code in Python file?
I have the following code in the file called stacktest.py inside my work folder in Visual Studio Code:

```<code>a = 'home'
b = 'hotel'
c = 'flat'

print(b)
</code>```

And I would like to use another Python file to edit this previous file, for example change:

```<code>b = 'hotel'
</code>```

For:

```<code>b = 'new value'
</code>```

So the new saved file would look like this:

```<code>a = 'home'
b = 'new value'
c = 'flat'

print(b)
</code>```

How should I go about doing this?

答:
Open in w+ to rewrite a line, note that if the new line has less characters than the line to replace, you will need to copy the entire contents of the file, manually replace it in a list, then rewrite it.</p>
```<code>with open("file.py", 'w+') as f:
    # jump to a certain line with .seek()
    f.seek(lineNumber)
    f.write("what you want the line to be")
</code>```

OwnerDisplayName: Brondby IF

Body:
I have the following code in the file called stacktest.py inside my work folder in Visual Studio Code:

a = 'home'
b = 'hotel'
c = 'flat'

print(b)

And I would like to use another Python file to edit this previous file, for example change:

b = 'hotel'

For:

b = 'new value'

So the new saved file would look like this:

a = 'home'
b = 'new value'
c = 'flat'

print(b)

How should I go about doing this?

Body:
Open in w+ to rewrite a line, note that if the new line has less characters than the line to replace, you will need to copy the entire contents of the file, manually replace it in a list, then rewrite it.

with open("file.py", 'w+') as f:
    # jump to a certain line with .seek()
    f.seek(lineNumber)
    f.write("what you want the line to be")


问:
Manually installing laravel/ui results in error
I'm trying to install the Laravel/ui package into an existing Laravel 7.28.4 project. I've installed the package on my local machine and uploaded the vendor/laravel/ui and vendor/composer folder manually to the remote server. I've done it this way because my server is a Raspberry PI 3 Model B with 1GB of RAM, composer ran out of memory when I tried installing the package. When I open the website or run any "php artisan" command (On the remote server), I get this error:

RuntimeException

In order to use the Auth::routes() method, please install the laravel/ui package.

What can I do to resolve this problem?

答:
Have you tried delete .php files within bootstrap/cache folder?
Laravel 8 UI issue
I follow watercayman comment its work for me</p>


问:
IIS 10 - ULR Rewrite rule for stopping Image Hotlinking - when working also affects the domain host itself
Windows 2016 Server running IIS 10 with the URL Rewrite Module installed.

The servers are set up in a server Farm.

I've been messing around with this for the last 48 hours and cannot, for the life of me, figure out why it is not working as it is supposed to work.

I've looked at a video showing how to set it up and how it works, and I've mimicked what was done in the video, and nothing, still cannot get it to work.

This is what happens.

Using this code below will work; as you notice, it has the pattern="Pattern: "
However, the leading site that hosts the images has its images replaced with the stop-hotlinking.png image as well.
So, in theory, it works, but the hosting site has no access to its images to display.

If I remove (pattern="Pattern: "), it does not work.

To sum it up.
The below code will display the "stop-hotlinking.png" image on all outside sites, as well as the hosting site.

```<code> <rewrite>
    <rules>
        <rule name="STOP-Hot-Linking" enabled="true" stopProcessing="true">
            <match url=".*\.(gif|jpg|png)$" />
            <conditions>
              <add input="{HTTP_REFERER}" pattern="Pattern: ^$" negate="true"/>
              <add input="{HTTP_REFERER}" pattern="Pattern: ^https?://(www\.)?domain\.com/.*$" negate="true"/>
            </conditions>
            <action type="Rewrite" url="/graph/stop-hotlinking.png" />
        </rule>
    </rules>
</rewrite>
</code>```

I even tried it with the pattern as this, and it will display the stop-hotlinking.png on all sites including the hosting site.

```<code><add input="{HTTP_REFERER}" pattern="^http://(.*\.)?domain\.com/.*$" negate="true"/>
</code>```

答:
I was assisted on another forum, and this was the issue.

I was testing the same image on multiple domains we own.

And that was the biggest problem, was the image would get cached, even when Google Tools was open, it would still cache it for whatever reason, we never could figure it out.
I changed to another image from the hosting site, and it started working.

We also found out that Google Chrome needed a referral meta tag in the head of the hosting sites page.

```<code><meta name="referrer" content="origin">
</code>```

Once all the above was taken care of and the following code in place. It started working.

```<code><rule name="Prevent Image Hotlinking" enabled="true" stopProcessing="true">
<match url=".*\.(jpg|jpeg|png|gif|bmp)$" />
<conditions>
   <add input="{HTTP_REFERER}" pattern="^https?://(www\.)?(?:DomainOne\.com|DomainTwo\.com|DomainThree\.com)/.*$" negate="true"/>
</conditions>
<action type="Rewrite" url="/graph/stop-hotlinking.png" logRewrittenUrl="true" />
</rule>
</code>```

In the above, you will see there are multiple domains, this is to allow images to be hosted on their domains, and all other domains will get the STOP image.

This is completed.

I want to think Jalpa for trying to assist.

And gr8gonzo from the other forum for helping me out in this long venture.

Body:
Windows 2016 Server running IIS 10 with the URL Rewrite Module installed.

The servers are set up in a server Farm.

I've been messing around with this for the last 48 hours and cannot, for the life of me, figure out why it is not working as it is supposed to work.

I've looked at a video showing how to set it up and how it works, and I've mimicked what was done in the video, and nothing, still cannot get it to work.

This is what happens.

Using this code below will work; as you notice, it has the pattern="Pattern: "
However, the leading site that hosts the images has its images replaced with the stop-hotlinking.png image as well.
So, in theory, it works, but the hosting site has no access to its images to display.

If I remove (pattern="Pattern: "), it does not work.

To sum it up.
The below code will display the "stop-hotlinking.png" image on all outside sites, as well as the hosting site.

 <rewrite>
    <rules>
        <rule name="STOP-Hot-Linking" enabled="true" stopProcessing="true">
            <match url=".*\.(gif|jpg|png)$" />
            <conditions>
              <add input="{HTTP_REFERER}" pattern="Pattern: ^$" negate="true"/>
              <add input="{HTTP_REFERER}" pattern="Pattern: ^https?://(www\.)?domain\.com/.*$" negate="true"/>
            </conditions>
            <action type="Rewrite" url="/graph/stop-hotlinking.png" />
        </rule>
    </rules>
</rewrite>

I even tried it with the pattern as this, and it will display the stop-hotlinking.png on all sites including the hosting site.

<add input="{HTTP_REFERER}" pattern="^http://(.*\.)?domain\.com/.*$" negate="true"/>

Body:
I was assisted on another forum, and this was the issue.

I was testing the same image on multiple domains we own.

And that was the biggest problem, was the image would get cached, even when Google Tools was open, it would still cache it for whatever reason, we never could figure it out.
I changed to another image from the hosting site, and it started working.

We also found out that Google Chrome needed a referral meta tag in the head of the hosting sites page.

<meta name="referrer" content="origin">

Once all the above was taken care of and the following code in place. It started working.

<rule name="Prevent Image Hotlinking" enabled="true" stopProcessing="true">
<match url=".*\.(jpg|jpeg|png|gif|bmp)$" />
<conditions>
   <add input="{HTTP_REFERER}" pattern="^https?://(www\.)?(?:DomainOne\.com|DomainTwo\.com|DomainThree\.com)/.*$" negate="true"/>
</conditions>
<action type="Rewrite" url="/graph/stop-hotlinking.png" logRewrittenUrl="true" />
</rule>

In the above, you will see there are multiple domains, this is to allow images to be hosted on their domains, and all other domains will get the STOP image.

This is completed.

I want to think Jalpa for trying to assist.

And gr8gonzo from the other forum for helping me out in this long venture.


问:
With AutoMapper, how can you read a settings file inside a profile if your source object is an IQueryable?
I am using AutoMapper in a .Net Core 3.1 project.

Inside one of the mapping profiles, for a member that exists only in the destination object, I need to set the value according to a value from the settings file (the appsettings.json file).

The source object is inside an IQueryable, which is passed IMapper.ProjectTo().Because of this, based on the AutoMapper documentation, this limits my options to

MapFrom (Expression-based)

ConvertUsing (Expression-based)

Ignore

NullSubstitute

Value transformers

IncludeMembers

Disappointingly, I cannot use Custom Type Converters or Custom Resolvers.

So given these constraints, I have been trying to inject the settings using an IOptions as shown below.

```<code>public class DepartmentProfile : Profile
{
    private static IOptions<ApiOptions> _apiOptions;

    public DepartmentProfile(IOptions<ApiOptions> apiOptions)
    {
        _apiOptions = apiOptions;

        CreateMap<Media, MediaDto>()
           .ForMember(m => m.DepartmentTitle, o => o.MapFrom(src => src.Department.Title))
           .ForMember(m => m.DepartmentOption, o => o.MapFrom(src => GetOptionValue()))
    }

    private static string GetOptionValue()
    {
        return _apiOptions.Value.Option;
    }
}
</code>```

The problem is I can't use this method since AutoMapper seems to want all mapping profile constructors to completely parameterless...

Furthermore, the code-base I'm working on has a very large number of mapping profiles that are all automatically registered using a single-line of code in the startup file- I don't really have the option of manually registering them at startup, and then passing extra options to them.

The code base is also architected in such a way that all the mapping logic really has to be done by the profile object itself- I cannot pass the object to another service after the automapper is done (for further mapping).

Does anyone know any way I can inject IOptions values to the mapping profile?

答:
Alternative approach is to create a method with the argument for default value.

```<code>public MediaDto ToDto(this Media entity, string defaultOption)
{
    return new MediaDto
    {
        DepartmentTitle = entity.DepartmentTitle,
        DepartmentOption = defaultOption
    };
}
</code>```

Notice that you should be able to use this method in top level projections of IQueryable.

```<code>var items = query.Where(id => id == givenId)
    .Select(entity => ToDto(entity, option.Value))
    .ToList();
</code>```

Benefits:

Comprehensible for other developers

Support any kind of mapping !!!important ;)

No dependencies on third party frameworks

Body:
I am using AutoMapper in a .Net Core 3.1 project.

Inside one of the mapping profiles, for a member that exists only in the destination object, I need to set the value according to a value from the settings file (the appsettings.json file).

The source object is inside an IQueryable, which is passed IMapper.ProjectTo().Because of this, based on the AutoMapper documentation, this limits my options to

MapFrom (Expression-based)

ConvertUsing (Expression-based)

Ignore

NullSubstitute

Value transformers

IncludeMembers

Disappointingly, I cannot use Custom Type Converters or Custom Resolvers.

So given these constraints, I have been trying to inject the settings using an IOptions as shown below.

public class DepartmentProfile : Profile
{
    private static IOptions<ApiOptions> _apiOptions;

    public DepartmentProfile(IOptions<ApiOptions> apiOptions)
    {
        _apiOptions = apiOptions;

        CreateMap<Media, MediaDto>()
           .ForMember(m => m.DepartmentTitle, o => o.MapFrom(src => src.Department.Title))
           .ForMember(m => m.DepartmentOption, o => o.MapFrom(src => GetOptionValue()))
    }

    private static string GetOptionValue()
    {
        return _apiOptions.Value.Option;
    }
}

The problem is I can't use this method since AutoMapper seems to want all mapping profile constructors to completely parameterless...

Furthermore, the code-base I'm working on has a very large number of mapping profiles that are all automatically registered using a single-line of code in the startup file- I don't really have the option of manually registering them at startup, and then passing extra options to them.

The code base is also architected in such a way that all the mapping logic really has to be done by the profile object itself- I cannot pass the object to another service after the automapper is done (for further mapping).

Does anyone know any way I can inject IOptions values to the mapping profile?

Body:
Alternative approach is to create a method with the argument for default value.

public MediaDto ToDto(this Media entity, string defaultOption)
{
    return new MediaDto
    {
        DepartmentTitle = entity.DepartmentTitle,
        DepartmentOption = defaultOption
    };
}

Notice that you should be able to use this method in top level projections of IQueryable.

var items = query.Where(id => id == givenId)
    .Select(entity => ToDto(entity, option.Value))
    .ToList();

Benefits:

Comprehensible for other developers

Support any kind of mapping !!!important ;)

No dependencies on third party frameworks


问:
Read local/linux files in Spark Scala code executing in Yarn Cluster Mode
How to access and read local file data in Spark executing in Yarn Cluster Mode.

```<code>local/linux file: /home/test_dir/test_file.csv

spark-submit --class "" --master yarn --deploy_mode cluster --files /home/test_dir/test_file.csv test.jar
</code>```

Spark code to read csv:

```<code>val test_data = spark.read.option("inferSchema", "true").option("header", "true).csv("/home/test_dir/test_file.csv")
val test_file_data = spark.read.option("inferSchema", "true").option("header", "true).csv("file:///home/test_dir/test_file.csv")
</code>```

The above sample spark-submit is failing with local file not-found error (/home/test_dir/test_file.csv)

Spark by defaults check for file in hdfs:// but my file is in local and should not be copied into hfds and should read only from local file system.

Any suggestions to resolve this error?

答:
Below solution worked for me:

```<code>local/linux file: /home/test_dir/test_file.csv

spark-submit --class "" --master yarn --deploy_mode cluster --files /home/test_dir/test_file.csv test.jar
</code>```

To access file passed in spark-submit:

```<code>import scala.io.Source
val lines = Source.fromPath("test_file.csv").getLines.toString
</code>```

Instead of specifying complete path, specify only file name that we want to read. As spark already takes copy of file across nodes, we can access data of file with only file name.

Body:
How to access and read local file data in Spark executing in Yarn Cluster Mode.

local/linux file: /home/test_dir/test_file.csv

spark-submit --class "" --master yarn --deploy_mode cluster --files /home/test_dir/test_file.csv test.jar

Spark code to read csv:

val test_data = spark.read.option("inferSchema", "true").option("header", "true).csv("/home/test_dir/test_file.csv")
val test_file_data = spark.read.option("inferSchema", "true").option("header", "true).csv("file:///home/test_dir/test_file.csv")

The above sample spark-submit is failing with local file not-found error (/home/test_dir/test_file.csv)

Spark by defaults check for file in hdfs:// but my file is in local and should not be copied into hfds and should read only from local file system.

Any suggestions to resolve this error?

Body:
Below solution worked for me:

local/linux file: /home/test_dir/test_file.csv

spark-submit --class "" --master yarn --deploy_mode cluster --files /home/test_dir/test_file.csv test.jar

To access file passed in spark-submit:

import scala.io.Source
val lines = Source.fromPath("test_file.csv").getLines.toString

Instead of specifying complete path, specify only file name that we want to read. As spark already takes copy of file across nodes, we can access data of file with only file name.


答:
I think the objective is to group by the columns based on the month and name. So the result dataframe will look like this -

```<code>date  amount
name     Month
Chlorox  7      2021-07-01, 2021-07-14, 2021-07-29     721
         8                              2021-08-11    6000
Suriname 8                  2021-08-12, 2021-08-19      13

</code>```

If that is the case - then here is a solution.

```<code>>>> import numpy as np
>>> import pandas as pd
>>> d = {
    'date' : ['2021-07-01', '2021-07-14', '2021-07-29', '2021-08-11', '2021-08-12', '2021-08-19', '2020-08-11', '2020-08-12', '2020-08-19'],
    'name' : ['Chlorox', 'Chlorox', 'Chlorox', 'Chlorox', 'Suriname', 'Suriname','Chlorox', 'Suriname', 'Suriname'],
    'amount': [1,20,700,6000,3,10,6500,300,150]
}

>>> df = pd.DataFrame(d)
</code>```

We will add a "Datetime" (dtype=datetime) column and a month (dtype=int) and a year column

```<code>>>> df['Datetime'] = pd.to_datetime( df.date)
>>> df['year'] = pd.DatetimeIndex(df['Datetime']).year
>>> df['month'] = pd.DatetimeIndex(df['Datetime']).month

>>> print(df.info())

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 9 entries, 0 to 8
Data columns (total 6 columns):
 #   Column    Non-Null Count  Dtype
---  ------    --------------  -----
 0   date      9 non-null      object
 1   name      9 non-null      object
 2   amount    9 non-null      int64
 3   Datetime  9 non-null      datetime64[ns]
 4   month     9 non-null      int64
 5   year      9 non-null      int64
dtypes: datetime64[ns](1), int64(3), object(2)
memory usage: 560.0+ bytes
None

>>> print(df)

date      name  amount   Datetime  month  year
0  2021-07-01   Chlorox       1 2021-07-01      7  2021
1  2021-07-14   Chlorox      20 2021-07-14      7  2021
2  2021-07-29   Chlorox     700 2021-07-29      7  2021
3  2021-08-11   Chlorox    6000 2021-08-11      8  2021
4  2021-08-12  Suriname       3 2021-08-12      8  2021
5  2021-08-19  Suriname      10 2021-08-19      8  2021
6  2020-08-11   Chlorox    6500 2020-08-11      8  2020
7  2020-08-12  Suriname     300 2020-08-12      8  2020
8  2020-08-19  Suriname     150 2020-08-19      8  2020

>>> # we will have this aggregate function to deal with concatenating string values together, and, for numerical additions we will use numpy.sum()
>>> def f1(s):
    return ', '.join(s)

>>> df_result = df.groupby(['name', 'year', 'month']).agg({'date': f1, 'amount': np.sum})

>>> print(df_result)

                                       date  amount
name     year month
Chlorox  2020 8                              2020-08-11    6500
         2021 7      2021-07-01, 2021-07-14, 2021-07-29     721
              8                              2021-08-11    6000
Suriname 2020 8                  2020-08-12, 2020-08-19     450
         2021 8                  2021-08-12, 2021-08-19      13

</code>```

See if this helps or leave a comment

Title: How do I get both the sum and an overlapping a list of dates that fall within a sliding window in a Pandas df?

Body:
I have a df like this:

date
name
amount

2021-07-01
'Chlorox'
1

2021-07-14
'Chlorox'
20

2021-07-29
'Chlorox'
700

2021-08-11
'Chlorox'
6000

2021-08-12
'Suriname'
3

2021-08-19
'Suriname'
10

and I'd like the sum of amounts within a one month period, (So 7-20 and 8-11 would be within the same period), plus all the dates that fall within that month range. So something like these results:

name
sum
dates

'Chlorox'
721
['2021-07-01', '2021-07-14', '2021-07-29']

'Chlorox'
6720
'2021-07-14', '2021-07-29', '2021-08-11'

'Suriname'
13
['2021-08-12', '2021-08-19']

I've been tinkering around with rolling() and groupby, but I've been struggling and unable to get overlapping dates!

Body:
I think the objective is to group by the columns based on the month and name. So the result dataframe will look like this -

date  amount
name     Month
Chlorox  7      2021-07-01, 2021-07-14, 2021-07-29     721
         8                              2021-08-11    6000
Suriname 8                  2021-08-12, 2021-08-19      13

If that is the case - then here is a solution.

>>> import numpy as np
>>> import pandas as pd
>>> d = {
    'date' : ['2021-07-01', '2021-07-14', '2021-07-29', '2021-08-11', '2021-08-12', '2021-08-19', '2020-08-11', '2020-08-12', '2020-08-19'],
    'name' : ['Chlorox', 'Chlorox', 'Chlorox', 'Chlorox', 'Suriname', 'Suriname','Chlorox', 'Suriname', 'Suriname'],
    'amount': [1,20,700,6000,3,10,6500,300,150]
}

>>> df = pd.DataFrame(d)

We will add a "Datetime" (dtype=datetime) column and a month (dtype=int) and a year column

>>> df['Datetime'] = pd.to_datetime( df.date)
>>> df['year'] = pd.DatetimeIndex(df['Datetime']).year
>>> df['month'] = pd.DatetimeIndex(df['Datetime']).month

>>> print(df.info())

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 9 entries, 0 to 8
Data columns (total 6 columns):
 #   Column    Non-Null Count  Dtype
---  ------    --------------  -----
 0   date      9 non-null      object
 1   name      9 non-null      object
 2   amount    9 non-null      int64
 3   Datetime  9 non-null      datetime64[ns]
 4   month     9 non-null      int64
 5   year      9 non-null      int64
dtypes: datetime64[ns](1), int64(3), object(2)
memory usage: 560.0+ bytes
None

>>> print(df)

date      name  amount   Datetime  month  year
0  2021-07-01   Chlorox       1 2021-07-01      7  2021
1  2021-07-14   Chlorox      20 2021-07-14      7  2021
2  2021-07-29   Chlorox     700 2021-07-29      7  2021
3  2021-08-11   Chlorox    6000 2021-08-11      8  2021
4  2021-08-12  Suriname       3 2021-08-12      8  2021
5  2021-08-19  Suriname      10 2021-08-19      8  2021
6  2020-08-11   Chlorox    6500 2020-08-11      8  2020
7  2020-08-12  Suriname     300 2020-08-12      8  2020
8  2020-08-19  Suriname     150 2020-08-19      8  2020

>>> # we will have this aggregate function to deal with concatenating string values together, and, for numerical additions we will use numpy.sum()
>>> def f1(s):
    return ', '.join(s)

>>> df_result = df.groupby(['name', 'year', 'month']).agg({'date': f1, 'amount': np.sum})

>>> print(df_result)

                                       date  amount
name     year month
Chlorox  2020 8                              2020-08-11    6500
         2021 7      2021-07-01, 2021-07-14, 2021-07-29     721
              8                              2021-08-11    6000
Suriname 2020 8                  2020-08-12, 2020-08-19     450
         2021 8                  2021-08-12, 2021-08-19      13

See if this helps or leave a comment


问:
How do you call an instance with one parameter?
```<code>public void remove(String name, int population, double area, String continent) {
    /* Make a new country object for removing */
    Country removeCountry = new Country(name, population, area, continent);

    /* Linear Search for the instance we want to remove */
    for (int i = 0; i < size; i++) {
        if (removeCountry.equals(catalogue[i])) {
            catalogue[i] = catalogue[size - 1];
            catalogue[size - 1] = null;
            size--;
        }
    }
}
</code>```

Okay so this is in a different class and I want to replace line 1 with,

```<code>public void remove(String name)
</code>```

but I can't because on the third line, I have to replace population and area with a value, for the continent, I could just replace it with "" and it would work.

```<code>Country removeCountry = new Country(name, [value], [value], "");
</code>```

In the main class, I want to be able to input this code,

```<code>myCountry.remove("Canada");
</code>```

So basically, I want to somehow override my primitive type parameters by I don't know how.

答:
If the Country.equals() method does not perform the comparison over the _population, _area or _continent data members (fields), any value can be given to the mentioned fields when creating an object instance.

public void remove(String name)
{
    /* Creating new object instance. */
    Country removeCountry = new Country(name, 0, 0.0, "");

    for (int i = 0; i < size; i++)
    {
        /* Country.equals() method must be independent of _population, _area and _continent */
        if (removeCountry.equals(catalogue[i]))
        {
            catalogue[i] = catalogue[size - 1];
            catalogue[size - 1] = null;
            size--;
        }
    }
}
```

Body:
public void remove(String name, int population, double area, String continent) {
    /* Make a new country object for removing */
    Country removeCountry = new Country(name, population, area, continent);

    /* Linear Search for the instance we want to remove */
    for (int i = 0; i < size; i++) {
        if (removeCountry.equals(catalogue[i])) {
            catalogue[i] = catalogue[size - 1];
            catalogue[size - 1] = null;
            size--;
        }
    }
}

Okay so this is in a different class and I want to replace line 1 with,

public void remove(String name)

but I can't because on the third line, I have to replace population and area with a value, for the continent, I could just replace it with "" and it would work.

Country removeCountry = new Country(name, [value], [value], "");

In the main class, I want to be able to input this code,

myCountry.remove("Canada");

So basically, I want to somehow override my primitive type parameters by I don't know how.


答:
You're overthinking it.

This part:

if (removeCountry.equals(catalogue[i])) {
```
<p>checks if the country you want to remove equals the country at index <code>i</code> in your catalogue, and <strong>you already lost</strong> because of this. Because that isn't what you want to do: You want to remove whatever country in the catalogue happens to have a certain name. <strong>Not</strong> the entry in the catalogue that exactly matches the entire record.</p>
<p>Just.. do what you want. You want to remove the item if its country name matches. So, write that:</p>
```if (catalogue[i].getName().equals(name)) {
 ...
}
```

Title: How do you call an instance with one parameter?

Body:
You're overthinking it.

This part:

if (removeCountry.equals(catalogue[i])) {

checks if the country you want to remove equals the country at index i in your catalogue, and you already lost because of this. Because that isn't what you want to do: You want to remove whatever country in the catalogue happens to have a certain name. Not the entry in the catalogue that exactly matches the entire record.

Just.. do what you want. You want to remove the item if its country name matches. So, write that:

if (catalogue[i].getName().equals(name)) {
 ...
}