问:
How to center Text within a List?
I want to center Text in a List, I want to see the text in Text in the middle. I tried some solutions, but the text remains leading.

I was expecting this to work:

```<code>struct ContentView: View {
    var body: some View {
        List {
            Text("Hello, world!")
               .frame(alignment: .center)
        }
    }
}
</code>```

The text remains leading. I also tried this, but not working:

```<code>.multilineTextAlignment(.center)
</code>```

The only solution is this:

```<code>HStack(alignment: .center) {
    Spacer()
    Text("Hello, world!")
    Spacer()
}
</code>```

But I can not imagine this is the right way, I mean I add literally 3 views just to center a simple text. Is there a simpler solution? When I have a large text and I use .multilineTextAlignment(.center), the text is centered. I want it to work with 1 line of text.

答:
You need to give all width for frame, otherwise it just fits text, so alignment has no effect.

This should work:

```<code>    List {
        Text("Hello, world!")
           .frame(maxWidth: .infinity, alignment: .center)
    }
</code>```

Title: How to center Text within a List?

Body:
I want to center Text in a List, I want to see the text in Text in the middle. I tried some solutions, but the text remains leading.

I was expecting this to work:

struct ContentView: View {
    var body: some View {
        List {
            Text("Hello, world!")
               .frame(alignment: .center)
        }
    }
}

The text remains leading. I also tried this, but not working:

.multilineTextAlignment(.center)

The only solution is this:

HStack(alignment: .center) {
    Spacer()
    Text("Hello, world!")
    Spacer()
}

But I can not imagine this is the right way, I mean I add literally 3 views just to center a simple text. Is there a simpler solution? When I have a large text and I use .multilineTextAlignment(.center), the text is centered. I want it to work with 1 line of text.

Body:
You need to give all width for frame, otherwise it just fits text, so alignment has no effect.

This should work:

    List {
        Text("Hello, world!")
           .frame(maxWidth: .infinity, alignment: .center)
    }


来源: stackexchange

问:
How to find non repeated numbers in an Array using JavaScript?
Dear all I'm trying to find non repeated value in an array using javascript.I have written some code but it not working properly ..can you guys tell me where is the problem.thanks.

var arr = [-1, 2, 5, 6, 2, 9, -1, 6, 5, -1, 3];
var n = arr.length;
var result = '';

function nonrep() {
  for (var i = 0; i < n; i++) {
    var j;
    for (j = 0; j < n; j++)
      if (i != j && arr[i] == arr[j]) {
        result = arr[i];
        break;
      }
    if (j == n)
      return arr[i];
  }
  return result;
}
console.log(nonrep())```

答:
Another simple approach

var arr = [1,1,2,3,3,4,4,5];

let duplicateArr = [];
var repeatorCheck = (item) => {
  const currentItemCount = arr.filter(val => val=== item).length;
  if(currentItemCount > 1) duplicateArr.push(item);
  return currentItemCount;
}
var result = arr.filter((item,index) => {
  var itemRepeaterCheck = !duplicateArr.includes(item) && repeatorCheck(item);
  if(itemRepeaterCheck === 1){
    return item;
  }
});
console.log(result);```

ContentLicense: CC BY-SA 4.0


问:
Extract content from blog
```<code>import scrapy
from scrapy.http import Request

class PushpaSpider(scrapy.Spider):
    name = 'pushpa'
    start_urls = ['https://davestruestories.medium.com']
    headers = {
        'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'
    }

    # custom settings
    custom_settings = {
        'CONCURRENT_REQUESTS_PER_DOMAIN': 1,
        'DOWNLOAD_DELAY': 1
    }

    def parse(self, response):
        link=response.xpath("//h1/a/@href").extract()
        for links in link:
            url = response.urljoin(links)
            yield Request(url, callback=self.parse_book,headers=self.headers)

    def parse_book(self, response):
        title=response.xpath("//h1/text()").get()
        content=response.xpath("//section/text()").getall()
        yield{
            'title':title,
            'article':content
            }
</code>```

I want to extract content from the blog but they provided me nothing these is page link https://davestruestories.medium.com/?p=169d7850744a as you see below this is the content I want to extract

答:
Your xpath for the content is not pointing to the correct element.
content=response.xpath("//section/text()").getall()

The data is available in the below xpath as I tested. It is in the
 tags which are the child elements of

content=response.xpath("//section/p/text()").getall()

You can also verify the xpaths in scrapy shell

Title: Extract content from blog

Body:
import scrapy
from scrapy.http import Request

class PushpaSpider(scrapy.Spider):
    name = 'pushpa'
    start_urls = ['https://davestruestories.medium.com']
    headers = {
        'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'
    }

    # custom settings
    custom_settings = {
        'CONCURRENT_REQUESTS_PER_DOMAIN': 1,
        'DOWNLOAD_DELAY': 1
    }

    def parse(self, response):
        link=response.xpath("//h1/a/@href").extract()
        for links in link:
            url = response.urljoin(links)
            yield Request(url, callback=self.parse_book,headers=self.headers)

    def parse_book(self, response):
        title=response.xpath("//h1/text()").get()
        content=response.xpath("//section/text()").getall()
        yield{
            'title':title,
            'article':content
            }

I want to extract content from the blog but they provided me nothing these is page link https://davestruestories.medium.com/?p=169d7850744a as you see below this is the content I want to extract

Body:
Your xpath for the content is not pointing to the correct element.
content=response.xpath("//section/text()").getall()

The data is available in the below xpath as I tested. It is in the <p> tags which are the child elements of <section>

content=response.xpath("//section/p/text()").getall()

You can also verify the xpaths in scrapy shell


问:
Perl advice - Taking in a file and changing contents
I have a request for some advice on how to approach this script I want to write in Perl. Basically I have a file that looks like :

```<code>  id: 1
  Relationship: ""
  name: shelby
  pet: 1
  color:4
</code>```

There are certain keywords such as pet and color that have numbers after then. I want to be able to take in a file and look for these keywords (there are 5 or 6 of them) and then change the number to the word that number corresponds to. That is to say for the keyword "Pet"---> 0 =dog, 1 = cat, 2=fish. And for the keyword "color" 0 = red, 1=blue,2=purple,3=brown,4=white. The script should find and change these numbers. The goal should be an output file that looks like:

```<code>      id: 1
      Relationship: ""
      name: shelby
      pet: cat
      color:white
</code>```

I've been struggling with how to do this for a while. I looked up online maybe I could do an array of hashes or something but I'm relatively new to Perl and don't know exactly how to even approach this problem.... Any advice would be much appreciated!

Thanks

答:
If there are not many cases, you can try something like this, to be run with perl -p:

```<code>if (/^id/)
{
    s/\d+/%h=(1=>"dog",2=>"warf",3=>"ee");$h{$&}/e;
}
if (/^other/)
{
    s/\d+/%h=(1=>"other_thing",3=>"etc",4=>"etc2");$h{$&}/e;
}
</code>```

EDIT:

To automate the tests, you can do something like (also taking the idea of hashes from zigdon):

```<code>my @interesting_tags = ("color", "pet");
my $regexp = "(" .  join("|" , @interesting_tags) . ")";

my %lookups = ( pet => [ "dog", "cat", "fish" ],
                color => [ "red", "blue", "purple", "brown", "white" ] );

while (<>)
{
    if (/$regexp/)
    {
        my $element = $&;
        s/\d+/$lookups{$element}[$&]/e;
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a request for some advice on how to approach this script I want to write in Perl. Basically I have a file that looks like :

  id: 1
  Relationship: ""
  name: shelby
  pet: 1
  color:4

There are certain keywords such as pet and color that have numbers after then. I want to be able to take in a file and look for these keywords (there are 5 or 6 of them) and then change the number to the word that number corresponds to. That is to say for the keyword "Pet"---> 0 =dog, 1 = cat, 2=fish. And for the keyword "color" 0 = red, 1=blue,2=purple,3=brown,4=white. The script should find and change these numbers. The goal should be an output file that looks like:

      id: 1
      Relationship: ""
      name: shelby
      pet: cat
      color:white

I've been struggling with how to do this for a while. I looked up online maybe I could do an array of hashes or something but I'm relatively new to Perl and don't know exactly how to even approach this problem.... Any advice would be much appreciated!

Thanks

Body:
If there are not many cases, you can try something like this, to be run with perl -p:

if (/^id/)
{
    s/\d+/%h=(1=>"dog",2=>"warf",3=>"ee");$h{$&}/e;
}
if (/^other/)
{
    s/\d+/%h=(1=>"other_thing",3=>"etc",4=>"etc2");$h{$&}/e;
}

EDIT:

To automate the tests, you can do something like (also taking the idea of hashes from zigdon):

my @interesting_tags = ("color", "pet");
my $regexp = "(" .  join("|" , @interesting_tags) . ")";

my %lookups = ( pet => [ "dog", "cat", "fish" ],
                color => [ "red", "blue", "purple", "brown", "white" ] );

while (<>)
{
    if (/$regexp/)
    {
        my $element = $&;
        s/\d+/$lookups{$element}[$&]/e;
    }
}


问:
What are the best practices for internal security standards in companies with large SAP investments?
I work in a large company, and I'm interested in best practices for internal security standards. We have a large ($500 million +) investment in SAP, and we also have .Net and a bit of Java EE in our internal environment.

I've found some documentation from MS and SAP, but it's outdated and not very specific.

So far, it looks like we could end up using Active Directory as the standard user store for all non-SAP applications, and SAP CUA / Portal for SAP applications.

Some concerns I have about AD are:

Being able to aggressively time-out for applications on shared computers (A small number of our applications run in remote offices in rural areas with a limited number of shared machines. In these cases, a supervisor with "power user" privilages could use an application, and then a clerk who should have only basic privaleges could use the same machine immediately after)

Being able to force the user to enter a username and password instead of just having the credentials read from the user's workstation - Because it's pulling the same credentials for the desktop and email, it won't currently ask users to log in. This is a concern for applications on shared computers as well. (See the explanation in the previous bullet)

As far as synchronization between AD and CUA is concerned, I want to approach this very carefully. We have a limited budget, and I want to make sure that if we end up putting something in place to synchronize the stores, that it's rock sold and provides excellent value. If we can't find something like this, I'd be comfortable coming back with a recommendation that the stores remain independent. SSO would be ideal, but I've worked with trying to get an SSO application up before SAML, and it wasn't pretty.

Acronyms:

SSO: Single Sign-On  SAML: Security

Assertion Markup Language

CUA: Central User Administration (For SAP)

答:
IMHO.
This is not good solution to use different users in one windows session. Especially users authenticated in AD.
Usually it will be going that USER1 running sap client without closing  , and work another USER2.
You get non-personified users. And don't forget users don't like perform all instructions.

We used thin client like citrix and SSO. It is full split data and authorization between users. And you have to use different sessions for users on workstation. The good think is no critical data  store on workstation.

Not good idea and not secure but you can use run as different users

application in Windows environment in same session.  But it is not secure solution for big company.

OwnerDisplayName: Kaiser Advisor

LastEditorDisplayName: Rich B


问:
Remove group when the user is removed django
I'm new to Django and I've created a registration form where, when a user signs up, it automatically creates a group with the same name as the user's username and puts the new user in it. In this way, every user is inside a unique user group (that happen to have the same name as the user inside it).

Now, my problem is that, if I delete the user, the group clearly won't be deleted as well. Is there a way to automatize this process? So, delete user --> delete the group he/she/it was in there?

My code

views.py

```<code>@unauthenticated_user
def register_user(request):
    if request.method == "POST":
        form = RegisterUserForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data['username']
            password = form.cleaned_data['password1']
            user = authenticate(username=username, password=password)
            login(request, user)
            messages.success(request, "Registration Succesfully")
            # every user is inside an unique group with its name
            Group.objects.get_or_create(name=username)
            group = Group.objects.get(name=username)
            group.user_set.add(user)
            user.save()
            return HttpResponseRedirect('register')
        else:
            pass
    else:
        form = RegisterUserForm()
    return render(request, 'authenticate/register_user.html', {
        'form': form,
    })
</code>```

答:
The solution was to use signals inside models.py such as

models.py

```<code>from django.dispatch import receiver
from django.db.models.signals import post_delete
from django.contrib.auth.models import Group

@receiver(post_delete, sender=User)
def delete_user_group(sender, instance, *arg, **kwargs):
    group = Group.objects.get(name=instance.username)
    group.delete()
</code>```

Body:
I'm new to Django and I've created a registration form where, when a user signs up, it automatically creates a group with the same name as the user's username and puts the new user in it. In this way, every user is inside a unique user group (that happen to have the same name as the user inside it).

Now, my problem is that, if I delete the user, the group clearly won't be deleted as well. Is there a way to automatize this process? So, delete user --> delete the group he/she/it was in there?

My code

views.py

@unauthenticated_user
def register_user(request):
    if request.method == "POST":
        form = RegisterUserForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data['username']
            password = form.cleaned_data['password1']
            user = authenticate(username=username, password=password)
            login(request, user)
            messages.success(request, "Registration Succesfully")
            # every user is inside an unique group with its name
            Group.objects.get_or_create(name=username)
            group = Group.objects.get(name=username)
            group.user_set.add(user)
            user.save()
            return HttpResponseRedirect('register')
        else:
            pass
    else:
        form = RegisterUserForm()
    return render(request, 'authenticate/register_user.html', {
        'form': form,
    })

Body:
The solution was to use signals inside models.py such as

models.py

from django.dispatch import receiver
from django.db.models.signals import post_delete
from django.contrib.auth.models import Group

@receiver(post_delete, sender=User)
def delete_user_group(sender, instance, *arg, **kwargs):
    group = Group.objects.get(name=instance.username)
    group.delete()


问:
Special function in Google Sheet

Hi everyone, please advise.

I can't come up with a combination of functions (MATCH,LOOKUP,etc.) in Google Sheets that would return the row number of the cell that matches the given rule in the given range. Moreover, I need to find this value from bottom to top.

I am attaching an image in which I show the invented function "FIRST_VALUE", which in this particular case should return the value "5", because just 5 rows above is the value 655.79, which is higher than the rule ">655".

Thank you very much!

答:
use:

```<code>=ROW()-INDEX(MAX(IF(INDIRECT("B1:B"&ROW())>655; ROW(INDIRECT("B1:B"&ROW())); )))
</code>```

Title: Special function in Google Sheet

Body:
use:

=ROW()-INDEX(MAX(IF(INDIRECT("B1:B"&ROW())>655; ROW(INDIRECT("B1:B"&ROW())); )))


问:
Simulating an if condition in the WHERE clause of an SQL query
I am trying to write a google BigQuery to select some records based on this condition:

```<code>if ID_parameter is not null:
   SELECT * WHERE ID=ID_parameter
else:
   SELECT * WHERE country_id=country_id_parameter and (name LIKE %name_parameter% OR name is null)
</code>```

The name_parameter should be optional but one of the ID_parameter or country_id_parameter must be provided.

Sorry, I am a newbie with SQL but I hope I stated what I want clearly.

答:
I miss the table name in the query, let's assume it's 'personnel'.
Suppose ID-parameter = 200, country_id_parameter = 'NL', name_parameter = '%bart%'

Maybe like this when the name is 'bart':

```<code>select * from personnel
where ID=200
or (ID=NULL and
    country_id='NL' and
    name LIKE '%bart%')
</code>```

Use this when the name is NULL:

```<code>select * from personnel
where ID=200
or (ID=NULL and
    country_id='NL')

</code>```

Body:
I am trying to write a google BigQuery to select some records based on this condition:

if ID_parameter is not null:
   SELECT * WHERE ID=ID_parameter
else:
   SELECT * WHERE country_id=country_id_parameter and (name LIKE %name_parameter% OR name is null)

The name_parameter should be optional but one of the ID_parameter or country_id_parameter must be provided.

Sorry, I am a newbie with SQL but I hope I stated what I want clearly.

Body:
I miss the table name in the query, let's assume it's 'personnel'.
Suppose ID-parameter = 200, country_id_parameter = 'NL', name_parameter = '%bart%'

Maybe like this when the name is 'bart':

select * from personnel
where ID=200
or (ID=NULL and
    country_id='NL' and
    name LIKE '%bart%')

Use this when the name is NULL:

select * from personnel
where ID=200
or (ID=NULL and
    country_id='NL')


问:
How to align content of a div to the bottom with css?
How to align content of a div to the bottom with css

Could anyone help complete this? Or at least point to the right direction?

I want it that way

This is my code:

.bbb{
text-align:center;
bottom: 20px;
}
.text-wi{
border-top:2px dashed #13aff2;
 padding: 5px 0 0 20px;
}

.haha{
 padding:5px
}
.widget-host {
  display: grid;
  grid-template-columns:auto auto;
  grid-gap: 20px;
}

.widget-host > div.host-woovn {
border: 1px solid #e9e9e9;
 padding: 0 5px 0 5px;
}
.button{
    background-color: #669900;
    text-align: center;
    color: #fff;
    cursor: pointer;
    font-weight: bold;
    font-size: 14px;
    padding: 8px 15px;
    display: inline-block;
    margin-bottom: 10px;
    height: initial;
    border-radius: 4px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="widget-host"><div class="host-woovn">
AAAAAAAAAAAAAAAAA<div class="text-wi">
 – A<br>
– B<br>
– C<br>
– D<br>
– C
</div>
 <div class="bbb"> AAAAA</div>
</div>
<div class="host-woovn">
 BBBBBBBBBBBBBBB<div class="text-wi">
– A<br>
– B<br>
– C<br>
– D<br>
– E<br>
– B<br>
– C<br>
– F</div>
<div class="bbb">BBBB</div>
 </div></div></code>```

It does not work as I would like. What I am doing wrong?

Any help is appreciated

答:
other styles like position: absolute etc. didnt work for me.
using css flex-box and grid are some of the easiest way you can align items.

i did change the html a little, i.e. making content on right and left separate div
CSS

```<code><!DOCTYPE html>
<html>
<body>
<style>

.widgethost{
background-color:green;
display: flex;
flex-direction: row;
justify-content:flex-start;

height:100vh;

}

.parent{
margin: 1rem;
color:white;
display:flex;
flex-direction:row;

display:flex;
flex-direction:column;
justify-content:space-between;

border:5px solid black;

}

a, a:visited, a:hover{
text-decoration:none;
color:black;
}

</style>

</code>```

HTML

```<code>
<div class="widgethost">
  <div class="parent aaa">
    <div class="host-woovn">
      AAAAAAAAAAAAAAAAA
    </div>
    <div class="text-wi">
      – A<br>
      – B<br>
      – C<br>
      – D<br>
      – C
    </div>
    <div class="bbb">
      <a href="/" target="_blank" class="button">AAAAA</a>
    </div>
  </div>
  <div class="parent bbb">
    <div class="host-woovn">
      BBBBBBBBBBBBBBB
    </div>
    <div class="text-wi">
      – A<br>
      – B<br>
      – C<br>
      – D<br>
      – E<br>
      – B<br>
      – C<br>
      – F
    </div>
    <div class="bbb">
      <a href="/" target="_blank" class="button">BBBB</a>
    </div>
  </div>
</div>

</body>
</html>
</code>```

Body:
How to align content of a div to the bottom with css

Could anyone help complete this? Or at least point to the right direction?

I want it that way

This is my code:

.bbb{
text-align:center;
bottom: 20px;
}
.text-wi{
border-top:2px dashed #13aff2;
 padding: 5px 0 0 20px;
}

.haha{
 padding:5px
}
.widget-host {
  display: grid;
  grid-template-columns:auto auto;
  grid-gap: 20px;
}

.widget-host > div.host-woovn {
border: 1px solid #e9e9e9;
 padding: 0 5px 0 5px;
}
.button{
    background-color: #669900;
    text-align: center;
    color: #fff;
    cursor: pointer;
    font-weight: bold;
    font-size: 14px;
    padding: 8px 15px;
    display: inline-block;
    margin-bottom: 10px;
    height: initial;
    border-radius: 4px;
}

AAAAAAAAAAAAAAAAA

 – A

– B

– C

– D

– C

 AAAAA

 BBBBBBBBBBBBBBB

– A

– B

– C

– D

– E

– B

– C

– F

BBBB

It does not work as I would like. What I am doing wrong?

Any help is appreciated

Body:
other styles like position: absolute etc. didnt work for me.
using css flex-box and grid are some of the easiest way you can align items.

i did change the html a little, i.e. making content on right and left separate div
CSS

<!DOCTYPE html>
<html>
<body>
<style>

.widgethost{
background-color:green;
display: flex;
flex-direction: row;
justify-content:flex-start;

height:100vh;

}

.parent{
margin: 1rem;
color:white;
display:flex;
flex-direction:row;

display:flex;
flex-direction:column;
justify-content:space-between;

border:5px solid black;

}

a, a:visited, a:hover{
text-decoration:none;
color:black;
}

</style>

HTML

<div class="widgethost">
  <div class="parent aaa">
    <div class="host-woovn">
      AAAAAAAAAAAAAAAAA
    </div>
    <div class="text-wi">
      – A<br>
      – B<br>
      – C<br>
      – D<br>
      – C
    </div>
    <div class="bbb">
      <a href="/" target="_blank" class="button">AAAAA</a>
    </div>
  </div>
  <div class="parent bbb">
    <div class="host-woovn">
      BBBBBBBBBBBBBBB
    </div>
    <div class="text-wi">
      – A<br>
      – B<br>
      – C<br>
      – D<br>
      – E<br>
      – B<br>
      – C<br>
      – F
    </div>
    <div class="bbb">
      <a href="/" target="_blank" class="button">BBBB</a>
    </div>
  </div>
</div>

</body>
</html>


问:
WordPress REST API Custom Endpoint with URL Parameter
I am trying to create a custom endpoint for the WordPress REST API and pass parameters through the URL.

The endpoint currently is:

/wp-json/v1/products/81838240219

What I am trying to achieve is an endpoint that looks like this and being able to retrieve the identifier parameter in the callback.

```<code>/wp-json/v1/products?identifier=81838240219

// Custom api endpoint test
function my_awesome_func( $data ) {
  $identifier = get_query_var( 'identifier' );
  return $identifier;
}
add_action( 'rest_api_init', function () {
register_rest_route( 'api/v1', '/products=(?P<id>\d+)', array(
    'methods' => 'GET',
    'callback' => 'my_awesome_func',
  ) );
} );
</code>```

答:
If you want to pass alphanumeric parameters, use [a-zA-Z0-9-] instead of \d

```<code>add_action( 'rest_api_init', function () {
    register_rest_route( 'namespace/v1', '/product/(?P<id>[a-zA-Z0-9-]+)', array(
        'methods' => 'GET',
        'callback' => 'my_awesome_func',
    ) );
} );
</code>```

Body:
I am trying to create a custom endpoint for the WordPress REST API and pass parameters through the URL.

The endpoint currently is:

/wp-json/v1/products/81838240219

What I am trying to achieve is an endpoint that looks like this and being able to retrieve the identifier parameter in the callback.

/wp-json/v1/products?identifier=81838240219

// Custom api endpoint test
function my_awesome_func( $data ) {
  $identifier = get_query_var( 'identifier' );
  return $identifier;
}
add_action( 'rest_api_init', function () {
register_rest_route( 'api/v1', '/products=(?P<id>\d+)', array(
    'methods' => 'GET',
    'callback' => 'my_awesome_func',
  ) );
} );

Body:
If you want to pass alphanumeric parameters, use [a-zA-Z0-9-] instead of \d

add_action( 'rest_api_init', function () {
    register_rest_route( 'namespace/v1', '/product/(?P<id>[a-zA-Z0-9-]+)', array(
        'methods' => 'GET',
        'callback' => 'my_awesome_func',
    ) );
} );


答:
If you look to html which you get from response, you will see that these information is empty (links)

You need made some changes:

```<code>import json
....

def parse(self, response):
        raw_data = response.xpath('//script[contains(text(),"__APOLLO_STATE__")]/text()').get()
        data = json.loads(raw_data[raw_data.index("{"):])
        links = [data[el].get("mediumUrl") for el in data if "mediumUrl" in data[el].keys()]
        for link in links:
            url = response.urljoin(link)
            yield Request(url, callback=self.parse_book,headers=self.headers)

....
</code>```

Title: Extract content from blog

Body:
If you look to html which you get from response, you will see that these information is empty (links)

You need made some changes:

import json
....

def parse(self, response):
        raw_data = response.xpath('//script[contains(text(),"__APOLLO_STATE__")]/text()').get()
        data = json.loads(raw_data[raw_data.index("{"):])
        links = [data[el].get("mediumUrl") for el in data if "mediumUrl" in data[el].keys()]
        for link in links:
            url = response.urljoin(link)
            yield Request(url, callback=self.parse_book,headers=self.headers)

....


问:
How to install Ruby 3.1.0 on MacOS Monterey
I am trying to install Ruby 3.1.0 using RVM on MacOS Monterey, v12.0.1, but it's returning an error while compiling.

I tried updating Homebrew, and uninstalling and reinstalling everything but I am getting the same error.

This is the error in the terminal window:

```<code>ruby-3.1.0 - #removing src/ruby-3.1.0 - please wait
Searching for binary rubies, this might take some time.
No binary rubies available for: osx/12.0/x86_64/ruby-3.1.0.
Continuing with compilation. Please read 'rvm help mount' to get more information on binary rubies.
Checking requirements for osx.
Certificates bundle '/usr/local/etc/openssl@1.1/cert.pem' is already up to date.
Requirements installation successful.
Installing Ruby from source to: /Users/sindhuja.n/.rvm/rubies/ruby-3.1.0, this may take a while depending on your cpu(s)...
ruby-3.1.0 - #downloading ruby-3.1.0, this may take a while depending on your connection...
ruby-3.1.0 - #extracting ruby-3.1.0 to /Users/sindhuja.n/.rvm/src/ruby-3.1.0 - please wait
ruby-3.1.0 - #configuring - please wait
ruby-3.1.0 - #post-configuration - please wait
ruby-3.1.0 - #compiling - please wait
Error running '__rvm_make -j12',
please read /Users/sindhuja.n/.rvm/log/1643979372_ruby-3.1.0/make.log

There has been an error while running make. Halting the installation.
</code>```

This is the error log file:

```<code>building .ext/include/x86_64-darwin21/rb_mjit_min_header-3.1.0.h
make[1]: Nothing to be done for `srcs'.
generating transdb.h
transdb.h updated
linking shared-library libruby.3.1.dylib
error in initial header file:
In file included from /var/folders/ky/347m_s3x7d15w435j_pvl2cc0000gn/T/20220204-43863-1rn0v3.c:1:
/var/folders/ky/347m_s3x7d15w435j_pvl2cc0000gn/T/20220204-43863-34xdve.h:7176:66: fatal error: expected identifier or '('
pthread_override_qos_class_end_np(pthread_override_t __override);#pragma clang assume_nonnull end
                                                                 ^
1 error generated.
make: *** [.ext/include/x86_64-darwin21/rb_mjit_min_header-3.1.0.h] Error 1
make: *** Waiting for unfinished jobs....
+__rvm_make:0> return
</code>```

答:
I had the same error for rbenv 3.1.0 with Monterey12.3beta & Xcode13.3beta.
but once I switched to Xcode13.0, the error's gone.

I guess the error's due to or related to clang version..

Body:
I am trying to install Ruby 3.1.0 using RVM on MacOS Monterey, v12.0.1, but it's returning an error while compiling.

I tried updating Homebrew, and uninstalling and reinstalling everything but I am getting the same error.

This is the error in the terminal window:

ruby-3.1.0 - #removing src/ruby-3.1.0 - please wait
Searching for binary rubies, this might take some time.
No binary rubies available for: osx/12.0/x86_64/ruby-3.1.0.
Continuing with compilation. Please read 'rvm help mount' to get more information on binary rubies.
Checking requirements for osx.
Certificates bundle '/usr/local/etc/openssl@1.1/cert.pem' is already up to date.
Requirements installation successful.
Installing Ruby from source to: /Users/sindhuja.n/.rvm/rubies/ruby-3.1.0, this may take a while depending on your cpu(s)...
ruby-3.1.0 - #downloading ruby-3.1.0, this may take a while depending on your connection...
ruby-3.1.0 - #extracting ruby-3.1.0 to /Users/sindhuja.n/.rvm/src/ruby-3.1.0 - please wait
ruby-3.1.0 - #configuring - please wait
ruby-3.1.0 - #post-configuration - please wait
ruby-3.1.0 - #compiling - please wait
Error running '__rvm_make -j12',
please read /Users/sindhuja.n/.rvm/log/1643979372_ruby-3.1.0/make.log

There has been an error while running make. Halting the installation.

This is the error log file:

building .ext/include/x86_64-darwin21/rb_mjit_min_header-3.1.0.h
make[1]: Nothing to be done for `srcs'.
generating transdb.h
transdb.h updated
linking shared-library libruby.3.1.dylib
error in initial header file:
In file included from /var/folders/ky/347m_s3x7d15w435j_pvl2cc0000gn/T/20220204-43863-1rn0v3.c:1:
/var/folders/ky/347m_s3x7d15w435j_pvl2cc0000gn/T/20220204-43863-34xdve.h:7176:66: fatal error: expected identifier or '('
pthread_override_qos_class_end_np(pthread_override_t __override);#pragma clang assume_nonnull end
                                                                 ^
1 error generated.
make: *** [.ext/include/x86_64-darwin21/rb_mjit_min_header-3.1.0.h] Error 1
make: *** Waiting for unfinished jobs....
+__rvm_make:0> return


问:
Load nib from file path
We might have a need for loading a nib using the results of

```<code>[NSBundle -pathForResource:ofType:inDirectory:forLocalization:]
</code>```

I thought this would be possible, but all the methods I can find only want the name not leading path info.

We are exploring a way to provide both fr-Fr and fr-CA through one code base.  Our client wants a fr-CA translation and we're afraid we might have another customer that wants a fr-Fr translation. I was thinking we could path to correct nib based on the selected language.

Thanks

答:
I don't understand the problem.
You can perfectly have two different NIBs, for France and Canada (french), as it's supported by Xcode.

Simply add new localization for your file(s):

Then use a view controller to load the NIB, with the initWithNibName method. The correct one will be used, depending on the device language settings.

Title: Load nib from file path

Body:
We might have a need for loading a nib using the results of

[NSBundle -pathForResource:ofType:inDirectory:forLocalization:]

I thought this would be possible, but all the methods I can find only want the name not leading path info.

We are exploring a way to provide both fr-Fr and fr-CA through one code base.  Our client wants a fr-CA translation and we're afraid we might have another customer that wants a fr-Fr translation. I was thinking we could path to correct nib based on the selected language.

Thanks


问:
Compilation error with webpack-encore-bundle in Symfony
I've a project in Symfony 5.3 where I manage JS with the webpack-encore-bundle.
I've been able to compile the JS files in the DEV environment, but I'm getting the following error when trying to deploy in PROD by running encore production:

```<code>[webpack-cli] TypeError: The 'compilation' argument must be an instance of Compilation
    at Function.getCompilationHooks (C:\www\dev\SugaSymfony\node_modules\webpack\lib\NormalModule.js:207:10)
    at C:\www\dev\SugaSymfony\node_modules\@symfony\webpack-encore\lib\webpack-manifest-plugin\index.js:56:24
    at _next37 (eval at create (C:\www\DEV\SugaSymfony\node_modules\tapable\lib\HookCodeFactory.js:19:10), <anonymous>:97:1)
    at _next15 (eval at create (C:\www\DEV\SugaSymfony\node_modules\tapable\lib\HookCodeFactory.js:19:10), <anonymous>:189:1)
    at Hook.eval [as call] (eval at create (C:\www\DEV\SugaSymfony\node_modules\tapable\lib\HookCodeFactory.js:19:10), <anonymous>:255:1)
    at Hook.CALL_DELEGATE [as _call] (C:\www\DEV\SugaSymfony\node_modules\tapable\lib\Hook.js:14:14)
    at Compiler.newCompilation (C:\www\DEV\SugaSymfony\node_modules\webpack\lib\Compiler.js:1109:26)
    at C:\www\DEV\SugaSymfony\node_modules\webpack\lib\Compiler.js:1153:29
    at Hook.eval [as callAsync] (eval at create (C:\www\DEV\SugaSymfony\node_modules\tapable\lib\HookCodeFactory.js:33:10), <anonymous>:22:1)
    at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (C:\www\DEV\SugaSymfony\node_modules\tapable\lib\Hook.js:18:14)
error Command failed with exit code 2.
</code>```

This error happens in a Windows 2012 Server with PHP 7.4 and Apache while the DEV environment is Windows 10, PHP 7.4 and the Symfony build-in server.

Here is my package.json file:

```<code>{
    "devDependencies": {
        "@symfony/stimulus-bridge": "^2.0.0",
        "@symfony/webpack-encore": "^1.0.0",
        "core-js": "^3.0.0",
        "regenerator-runtime": "^0.13.2",
        "stimulus": "^2.0.0",
        "webpack-notifier": "^1.6.0"
    },
    "license": "UNLICENSED",
    "private": true,
    "scripts": {
        "dev-server": "encore dev-server",
        "dev": "encore dev",
        "watch": "encore dev --watch",
        "build": "encore production --progress"
    },
    "dependencies": {
        "@popperjs/core": "^2.10.1",
        "bootstrap": "^5.1.1",
        "bootstrap-icons": "^1.5.0",
        "file-loader": "6.0.0",
        "jquery": "^3.6.0",
        "jquery-ui": "^1.13.0"
    }
}
</code>```

And my webpack.config.js file:

```<code>const Encore = require('@symfony/webpack-encore');

// Manually configure the runtime environment if not already configured yet by the "encore" command.
// It's useful when you use tools that rely on webpack.config.js file.
if (!Encore.isRuntimeEnvironmentConfigured()) {
    Encore.configureRuntimeEnvironment(process.env.NODE_ENV || 'dev');
}

Encore
    // directory where compiled assets will be stored
    .setOutputPath('public/build/')
    // public path used by the web server to access the output path
    .setPublicPath('/DEV/SugaSymfony/public/build')
    // only needed for CDN's or sub-directory deploy
    .setManifestKeyPrefix('build/')

    /*
     * ENTRY CONFIG
     *
     * Each entry will result in one JavaScript file (e.g. app.js)
     * and one CSS file (e.g. app.css) if your JavaScript imports CSS.
     */
    .addEntry('app', './assets/app.js')

    // page specific
    .addEntry('showDocs', './assets/showDocs.js')
    .addEntry('certificadoQualificacao', './assets/certificadoQualificacao.js')
    .addEntry('novaQualificacao', './assets/novaQualificacao.js')
    .addEntry('novaEspecificacao', './assets/novaEspecificacao.js')
    .addEntry('novoSimulador', './assets/novoSimulador.js')
    .addEntry('novaOrganizacao', './assets/novaOrganizacao.js')
    .addEntry('novaSpecAdm', './assets/novaSpecAdm.js')

    // enables the Symfony UX Stimulus bridge (used in assets/bootstrap.js)
    .enableStimulusBridge('./assets/controllers.json')

    // When enabled, Webpack "splits" your files into smaller pieces for greater optimization.
    .splitEntryChunks()

    // will require an extra script tag for runtime.js
    // but, you probably want this, unless you're building a single-page app
    .enableSingleRuntimeChunk()

    /*
     * FEATURE CONFIG
     *
     * Enable & configure other features below. For a full
     * list of features, see:
     * https://symfony.com/doc/current/frontend.html#adding-more-features
     */
    .cleanupOutputBeforeBuild()
    .enableBuildNotifications()
    .enableSourceMaps(!Encore.isProduction())
    // enables hashed filenames (e.g. app.abc123.css)
    .enableVersioning(Encore.isProduction())

    .configureBabel((config) => {
        config.plugins.push('@babel/plugin-proposal-class-properties');
    })

    // enables @babel/preset-env polyfills
    .configureBabelPresetEnv((config) => {
        config.useBuiltIns = 'usage';
        config.corejs = 3;
    })

     .copyFiles({
         from: './assets/img'
     })

    // enables Sass/SCSS support
    //.enableSassLoader()

    // uncomment if you use TypeScript
    //.enableTypeScriptLoader()

    // uncomment if you use React
    //.enableReactPreset()

    // uncomment to get integrity="..." attributes on your script & link tags
    // requires WebpackEncoreBundle 1.4 or higher
    //.enableIntegrityHashes(Encore.isProduction())

    // uncomment if you're having problems with a jQuery plugin
    .autoProvidejQuery()
;

module.exports = Encore.getWebpackConfig();
</code>```

and, finally, my composer.json file:

```<code>{
    "type": "project",
    "license": "proprietary",
    "require": {
        "php": "^7.4",
        "ext-ctype": "*",
        "ext-iconv": "*",
        "amphp/http-client": "^4.6",
        "composer/package-versions-deprecated": "1.11.99.3",
        "doctrine/annotations": "^1.0",
        "doctrine/doctrine-bundle": "^2.3",
        "doctrine/doctrine-migrations-bundle": "^3.0",
        "doctrine/orm": "^2.7",
        "it/input-mask-bundle": "^1.3",
        "laminas/laminas-zendframework-bridge": "^1.3",
        "ocramius/proxy-manager": "^2.12",
        "phpdocumentor/reflection-docblock": "^5.2",
        "pugx/autocompleter-bundle": "^1.7",
        "sensio/framework-extra-bundle": "^5.1",
        "symfony/apache-pack": "^1.0",
        "symfony/asset": "5.3.*",
        "symfony/console": "5.3.*",
        "symfony/dotenv": "5.3.*",
        "symfony/expression-language": "5.3.*",
        "symfony/flex": "^1.1",
        "symfony/form": "5.3.*",
        "symfony/framework-bundle": "5.3.*",
        "symfony/http-client": "5.3.*",
        "symfony/intl": "5.3.*",
        "symfony/ldap": "5.3.*",
        "symfony/monolog-bundle": "^3.1",
        "symfony/phpunit-bridge": "^5.3",
        "symfony/process": "5.3.*",
        "symfony/property-access": "5.3.*",
        "symfony/property-info": "5.3.*",
        "symfony/proxy-manager-bridge": "5.3.*",
        "symfony/runtime": "5.3.*",
        "symfony/security-bundle": "5.3.*",
        "symfony/serializer": "5.3.*",
        "symfony/swiftmailer-bundle": "^3.1",
        "symfony/translation": "5.3.*",
        "symfony/twig-bundle": "5.3.*",
        "symfony/validator": "5.3.*",
        "symfony/web-link": "5.3.*",
        "symfony/webpack-encore-bundle": "^1.12",
        "symfony/yaml": "5.3.*",
        "anac/checks": "^1.0.2"
    },
    "require-dev": {
        "phpunit/phpunit": "^9.5",
        "symfony/browser-kit": "5.3.*",
        "symfony/css-selector": "5.3.*",
        "symfony/debug-bundle": "5.3.*",
        "symfony/maker-bundle": "^1.0",
        "symfony/stopwatch": "5.3.*",
        "symfony/web-profiler-bundle": "5.3.*",
        "symfony/web-server-bundle": "4.4.*"
    },
    "config": {
        "preferred-install": {
            "*": "dist"
        },
        "sort-packages": true
    },
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "App\\Tests\\": "tests/"
        }
    },
    "replace": {
        "paragonie/random_compat": "2.*",
        "symfony/polyfill-ctype": "*",
        "symfony/polyfill-iconv": "*",
        "symfony/polyfill-php71": "*",
        "symfony/polyfill-php70": "*",
        "symfony/polyfill-php56": "*"
    },
    "scripts": {
        "auto-scripts": {
            "cache:clear": "symfony-cmd",
            "assets:install %PUBLIC_DIR%": "symfony-cmd"
        },
        "post-install-cmd": [
            "@auto-scripts"
        ],
        "post-update-cmd": [
            "@auto-scripts"
        ]
    },
    "conflict": {
        "symfony/symfony": "*"
    },
    "extra": {
        "symfony": {
            "allow-contrib": false,
            "require": "5.3.*"
        }
    },
    "repositories": [
        {
            "type": "vcs",
            "url": "https://bitbucket.org/********"
        }
    ]
}
</code>```

From what I've searched, it appears the problem might be having two version of webpack installed, but I couldn't verify that. I've tried some suggested solutions, like reinstalling Node.js, erasing the node_modules directory among others without success.

Thanks for the help.

答:
I also encountered this error with webpack. I solved the problem by adding camelCase letters into the path to the directory in which the command is executed.

Let's take the following case:

I develop an application in the directory :

```<code>C:\Users\username\Desktop\myApp
</code>```

I compile the assets of this application with webpack. The Compilation type error is triggered if I execute the npm run dev command in c:\users\username\desktop\myapp because webpack can't find the node_modules folder. To fix the error you just have to run your command into the right directory with also camelCase letters.

```<code>C:\Users\username\Desktop\myApp> npm run dev
</code>```

Webpack should find the node_modules folder and you won't have any more errors.

Body:
I've a project in Symfony 5.3 where I manage JS with the webpack-encore-bundle.
I've been able to compile the JS files in the DEV environment, but I'm getting the following error when trying to deploy in PROD by running encore production:

[webpack-cli] TypeError: The 'compilation' argument must be an instance of Compilation
    at Function.getCompilationHooks (C:\www\dev\SugaSymfony\node_modules\webpack\lib\NormalModule.js:207:10)
    at C:\www\dev\SugaSymfony\node_modules\@symfony\webpack-encore\lib\webpack-manifest-plugin\index.js:56:24
    at _next37 (eval at create (C:\www\DEV\SugaSymfony\node_modules\tapable\lib\HookCodeFactory.js:19:10), <anonymous>:97:1)
    at _next15 (eval at create (C:\www\DEV\SugaSymfony\node_modules\tapable\lib\HookCodeFactory.js:19:10), <anonymous>:189:1)
    at Hook.eval [as call] (eval at create (C:\www\DEV\SugaSymfony\node_modules\tapable\lib\HookCodeFactory.js:19:10), <anonymous>:255:1)
    at Hook.CALL_DELEGATE [as _call] (C:\www\DEV\SugaSymfony\node_modules\tapable\lib\Hook.js:14:14)
    at Compiler.newCompilation (C:\www\DEV\SugaSymfony\node_modules\webpack\lib\Compiler.js:1109:26)
    at C:\www\DEV\SugaSymfony\node_modules\webpack\lib\Compiler.js:1153:29
    at Hook.eval [as callAsync] (eval at create (C:\www\DEV\SugaSymfony\node_modules\tapable\lib\HookCodeFactory.js:33:10), <anonymous>:22:1)
    at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (C:\www\DEV\SugaSymfony\node_modules\tapable\lib\Hook.js:18:14)
error Command failed with exit code 2.

This error happens in a Windows 2012 Server with PHP 7.4 and Apache while the DEV environment is Windows 10, PHP 7.4 and the Symfony build-in server.

Here is my package.json file:

{
    "devDependencies": {
        "@symfony/stimulus-bridge": "^2.0.0",
        "@symfony/webpack-encore": "^1.0.0",
        "core-js": "^3.0.0",
        "regenerator-runtime": "^0.13.2",
        "stimulus": "^2.0.0",
        "webpack-notifier": "^1.6.0"
    },
    "license": "UNLICENSED",
    "private": true,
    "scripts": {
        "dev-server": "encore dev-server",
        "dev": "encore dev",
        "watch": "encore dev --watch",
        "build": "encore production --progress"
    },
    "dependencies": {
        "@popperjs/core": "^2.10.1",
        "bootstrap": "^5.1.1",
        "bootstrap-icons": "^1.5.0",
        "file-loader": "6.0.0",
        "jquery": "^3.6.0",
        "jquery-ui": "^1.13.0"
    }
}

And my webpack.config.js file:

const Encore = require('@symfony/webpack-encore');

// Manually configure the runtime environment if not already configured yet by the "encore" command.
// It's useful when you use tools that rely on webpack.config.js file.
if (!Encore.isRuntimeEnvironmentConfigured()) {
    Encore.configureRuntimeEnvironment(process.env.NODE_ENV || 'dev');
}

Encore
    // directory where compiled assets will be stored
    .setOutputPath('public/build/')
    // public path used by the web server to access the output path
    .setPublicPath('/DEV/SugaSymfony/public/build')
    // only needed for CDN's or sub-directory deploy
    .setManifestKeyPrefix('build/')

    /*
     * ENTRY CONFIG
     *
     * Each entry will result in one JavaScript file (e.g. app.js)
     * and one CSS file (e.g. app.css) if your JavaScript imports CSS.
     */
    .addEntry('app', './assets/app.js')

    // page specific
    .addEntry('showDocs', './assets/showDocs.js')
    .addEntry('certificadoQualificacao', './assets/certificadoQualificacao.js')
    .addEntry('novaQualificacao', './assets/novaQualificacao.js')
    .addEntry('novaEspecificacao', './assets/novaEspecificacao.js')
    .addEntry('novoSimulador', './assets/novoSimulador.js')
    .addEntry('novaOrganizacao', './assets/novaOrganizacao.js')
    .addEntry('novaSpecAdm', './assets/novaSpecAdm.js')

    // enables the Symfony UX Stimulus bridge (used in assets/bootstrap.js)
    .enableStimulusBridge('./assets/controllers.json')

    // When enabled, Webpack "splits" your files into smaller pieces for greater optimization.
    .splitEntryChunks()

    // will require an extra script tag for runtime.js
    // but, you probably want this, unless you're building a single-page app
    .enableSingleRuntimeChunk()

    /*
     * FEATURE CONFIG
     *
     * Enable & configure other features below. For a full
     * list of features, see:
     * https://symfony.com/doc/current/frontend.html#adding-more-features
     */
    .cleanupOutputBeforeBuild()
    .enableBuildNotifications()
    .enableSourceMaps(!Encore.isProduction())
    // enables hashed filenames (e.g. app.abc123.css)
    .enableVersioning(Encore.isProduction())

    .configureBabel((config) => {
        config.plugins.push('@babel/plugin-proposal-class-properties');
    })

    // enables @babel/preset-env polyfills
    .configureBabelPresetEnv((config) => {
        config.useBuiltIns = 'usage';
        config.corejs = 3;
    })

     .copyFiles({
         from: './assets/img'
     })

    // enables Sass/SCSS support
    //.enableSassLoader()

    // uncomment if you use TypeScript
    //.enableTypeScriptLoader()

    // uncomment if you use React
    //.enableReactPreset()

    // uncomment to get integrity="..." attributes on your script & link tags
    // requires WebpackEncoreBundle 1.4 or higher
    //.enableIntegrityHashes(Encore.isProduction())

    // uncomment if you're having problems with a jQuery plugin
    .autoProvidejQuery()
;

module.exports = Encore.getWebpackConfig();

and, finally, my composer.json file:

{
    "type": "project",
    "license": "proprietary",
    "require": {
        "php": "^7.4",
        "ext-ctype": "*",
        "ext-iconv": "*",
        "amphp/http-client": "^4.6",
        "composer/package-versions-deprecated": "1.11.99.3",
        "doctrine/annotations": "^1.0",
        "doctrine/doctrine-bundle": "^2.3",
        "doctrine/doctrine-migrations-bundle": "^3.0",
        "doctrine/orm": "^2.7",
        "it/input-mask-bundle": "^1.3",
        "laminas/laminas-zendframework-bridge": "^1.3",
        "ocramius/proxy-manager": "^2.12",
        "phpdocumentor/reflection-docblock": "^5.2",
        "pugx/autocompleter-bundle": "^1.7",
        "sensio/framework-extra-bundle": "^5.1",
        "symfony/apache-pack": "^1.0",
        "symfony/asset": "5.3.*",
        "symfony/console": "5.3.*",
        "symfony/dotenv": "5.3.*",
        "symfony/expression-language": "5.3.*",
        "symfony/flex": "^1.1",
        "symfony/form": "5.3.*",
        "symfony/framework-bundle": "5.3.*",
        "symfony/http-client": "5.3.*",
        "symfony/intl": "5.3.*",
        "symfony/ldap": "5.3.*",
        "symfony/monolog-bundle": "^3.1",
        "symfony/phpunit-bridge": "^5.3",
        "symfony/process": "5.3.*",
        "symfony/property-access": "5.3.*",
        "symfony/property-info": "5.3.*",
        "symfony/proxy-manager-bridge": "5.3.*",
        "symfony/runtime": "5.3.*",
        "symfony/security-bundle": "5.3.*",
        "symfony/serializer": "5.3.*",
        "symfony/swiftmailer-bundle": "^3.1",
        "symfony/translation": "5.3.*",
        "symfony/twig-bundle": "5.3.*",
        "symfony/validator": "5.3.*",
        "symfony/web-link": "5.3.*",
        "symfony/webpack-encore-bundle": "^1.12",
        "symfony/yaml": "5.3.*",
        "anac/checks": "^1.0.2"
    },
    "require-dev": {
        "phpunit/phpunit": "^9.5",
        "symfony/browser-kit": "5.3.*",
        "symfony/css-selector": "5.3.*",
        "symfony/debug-bundle": "5.3.*",
        "symfony/maker-bundle": "^1.0",
        "symfony/stopwatch": "5.3.*",
        "symfony/web-profiler-bundle": "5.3.*",
        "symfony/web-server-bundle": "4.4.*"
    },
    "config": {
        "preferred-install": {
            "*": "dist"
        },
        "sort-packages": true
    },
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "App\\Tests\\": "tests/"
        }
    },
    "replace": {
        "paragonie/random_compat": "2.*",
        "symfony/polyfill-ctype": "*",
        "symfony/polyfill-iconv": "*",
        "symfony/polyfill-php71": "*",
        "symfony/polyfill-php70": "*",
        "symfony/polyfill-php56": "*"
    },
    "scripts": {
        "auto-scripts": {
            "cache:clear": "symfony-cmd",
            "assets:install %PUBLIC_DIR%": "symfony-cmd"
        },
        "post-install-cmd": [
            "@auto-scripts"
        ],
        "post-update-cmd": [
            "@auto-scripts"
        ]
    },
    "conflict": {
        "symfony/symfony": "*"
    },
    "extra": {
        "symfony": {
            "allow-contrib": false,
            "require": "5.3.*"
        }
    },
    "repositories": [
        {
            "type": "vcs",
            "url": "https://bitbucket.org/********"
        }
    ]
}

From what I've searched, it appears the problem might be having two version of webpack installed, but I couldn't verify that. I've tried some suggested solutions, like reinstalling Node.js, erasing the node_modules directory among others without success.

Thanks for the help.

Body:
I also encountered this error with webpack. I solved the problem by adding camelCase letters into the path to the directory in which the command is executed.

Let's take the following case:

I develop an application in the directory :

C:\Users\username\Desktop\myApp

I compile the assets of this application with webpack. The Compilation type error is triggered if I execute the npm run dev command in c:\users\username\desktop\myapp because webpack can't find the node_modules folder. To fix the error you just have to run your command into the right directory with also camelCase letters.

C:\Users\username\Desktop\myApp> npm run dev

Webpack should find the node_modules folder and you won't have any more errors.


问:
_ModuleNotFoundError: No module named 'first'
image of the code

the image of cmd and the error:( ModuleNotFoundError: No module named 'first'

what should I do to solve this problem by the way all the code is ok I followed all the steps like https://www.youtube.com/watch?v=jBzwzrDvZ18

答:
Your app name is first, not my app.

This code

```<code>path('', include('myapp.urls'))
</code>```

means: "Go to module (app) myapp find urls.py here and include every url found in urlpatterns list".

So you have to change it to

```<code>path('', include('first.urls'))
</code>```

for it to work

TO BE NOTED

Read How To Ask article. DO NOT paste images or image links of code, but code itself, as it improves readability and noone needs to jump between browser tabs to help you. Also include full stacktraces of exception for ease of defining the problem

Body:
Your app name is first, not my app.

This code

path('', include('myapp.urls'))

means: "Go to module (app) myapp find urls.py here and include every url found in urlpatterns list".

So you have to change it to

path('', include('first.urls'))

for it to work

TO BE NOTED

Read How To Ask article. DO NOT paste images or image links of code, but code itself, as it improves readability and noone needs to jump between browser tabs to help you. Also include full stacktraces of exception for ease of defining the problem


问:
Achieving numpy like fast interpolation in Fortran
I have a numerical routine that I need to run to solve a certain equation, which contains a few nested four loops. I initially wrote this routine into Python, using numba.jit to achieve an acceptable performance. For large system sizes however, this method becomes quite slow, so I have been rewriting the routine into Fortran hoping to achieve a speed-up. However I have found that my Fortran version is much slower than the first version in Python, by a factor of 2-3.

I believe the bottleneck is a linear interpolation function that is called at each innermost loop. In the Python implementation I use numpy.interp, which seems to be pretty fast when combined with numba.jit. In Fortran I wrote my own interpolation function, which reads,

```<code>  complex*16 function interp(x_dat, y_dat, N_dat, x)
    implicit none
    integer, intent(in) :: N_dat
    real*8, dimension(N_dat), intent(in) :: x_dat
    complex*16, dimension(N_dat), intent(in) :: y_dat
    real*8, intent(in) :: x

    complex*16 :: y, y1, y2
    integer :: i, i1, i2, im

    if(x <= x_dat(1)) then
      y = y_dat(1)
    else if(x >= x_dat(N_dat)) then
      y = y_dat(N_dat)
    else
      im = MINLOC(DABS(x_dat - x), DIM=1)
      if(x_dat(im) >=x ) then
        i1 = im
        i2 = im - 1
      else
        i1 = im + 1
        i2 = im
      end if

      y1 = y_dat(i1)
      y2 = y_dat(i2)

      y = y1 + (x-x_dat(i1))*(y2 - y1)/(x_dat(i2) - x_dat(i1))
    end if
    interp = y
    return
  end function interp

</code>```

Note that I need to interpolate complex data. If my diagnostics are correct this function is much slower than numpy.interp, which, since the interpolation has to be called in each loop, greatly reduces the speed of the whole program.

Does anyone know if there is a way to achieve Numpy like interpolation speeds in Fortran? Or if my interpolation function as shown above here is somehow horribly inefficient? I don't have much experience coding Fortran yet.

Thanks!

答:
At a guess (and see @IanBush's comments if you want to enable us to do better than guessing), it's the line

```<code>im = MINLOC(DABS(x_dat - x), DIM=1)
</code>```

which is taking all your time, as this line is O(N) in the size of x_dat, where everything else is O(1).

If x_dat is linearly spaced then you can replace this line with

```<code>im = 1 + nint((N_dat-1)*(x-x_dat(1))/(x_dat(N_dat)-x_dat(1)))
</code>```

or better yet, skip im entirely and calculate i1 and i2 as

```<code>i1 = 1 + floor((N_dat-1)*(x-x_dat(1))/(x_dat(N_dat)-x_dat(1)))
i2 = i1 + 1
</code>```

If x_dat is not linearly spaced, but has other useful properties, then you want to use these properties to calculate im if possible.

Body:
I have a numerical routine that I need to run to solve a certain equation, which contains a few nested four loops. I initially wrote this routine into Python, using numba.jit to achieve an acceptable performance. For large system sizes however, this method becomes quite slow, so I have been rewriting the routine into Fortran hoping to achieve a speed-up. However I have found that my Fortran version is much slower than the first version in Python, by a factor of 2-3.

I believe the bottleneck is a linear interpolation function that is called at each innermost loop. In the Python implementation I use numpy.interp, which seems to be pretty fast when combined with numba.jit. In Fortran I wrote my own interpolation function, which reads,

  complex*16 function interp(x_dat, y_dat, N_dat, x)
    implicit none
    integer, intent(in) :: N_dat
    real*8, dimension(N_dat), intent(in) :: x_dat
    complex*16, dimension(N_dat), intent(in) :: y_dat
    real*8, intent(in) :: x

    complex*16 :: y, y1, y2
    integer :: i, i1, i2, im

    if(x <= x_dat(1)) then
      y = y_dat(1)
    else if(x >= x_dat(N_dat)) then
      y = y_dat(N_dat)
    else
      im = MINLOC(DABS(x_dat - x), DIM=1)
      if(x_dat(im) >=x ) then
        i1 = im
        i2 = im - 1
      else
        i1 = im + 1
        i2 = im
      end if

      y1 = y_dat(i1)
      y2 = y_dat(i2)

      y = y1 + (x-x_dat(i1))*(y2 - y1)/(x_dat(i2) - x_dat(i1))
    end if
    interp = y
    return
  end function interp

Note that I need to interpolate complex data. If my diagnostics are correct this function is much slower than numpy.interp, which, since the interpolation has to be called in each loop, greatly reduces the speed of the whole program.

Does anyone know if there is a way to achieve Numpy like interpolation speeds in Fortran? Or if my interpolation function as shown above here is somehow horribly inefficient? I don't have much experience coding Fortran yet.

Thanks!

Body:
At a guess (and see @IanBush's comments if you want to enable us to do better than guessing), it's the line

im = MINLOC(DABS(x_dat - x), DIM=1)

which is taking all your time, as this line is O(N) in the size of x_dat, where everything else is O(1).

If x_dat is linearly spaced then you can replace this line with

im = 1 + nint((N_dat-1)*(x-x_dat(1))/(x_dat(N_dat)-x_dat(1)))

or better yet, skip im entirely and calculate i1 and i2 as

i1 = 1 + floor((N_dat-1)*(x-x_dat(1))/(x_dat(N_dat)-x_dat(1)))
i2 = i1 + 1

If x_dat is not linearly spaced, but has other useful properties, then you want to use these properties to calculate im if possible.


问:
Hiding error messages if writing to a file fails in a Windows .BAT script
i just subscribe here.

I would want to hide the "Acces is denied." error message in case writing to a read-only file fails. Could someone tell me why the following code doesn't work as expected ? I'm using Windows 10.

```<code>:: This file is assumed to be read-only.
echo( >"MyReadOnlyFile.txt" 2>nul
( echo( ) >"MyReadOnlyFile.txt" 2>nul
</code>```

In both case the "Access is denied." message is displayed, although the following "How-to: Redirection" page at SS64 says the contrary: https://ss64.com/nt/syntax-redirection.html

```<code>Redirect to NUL (hide errors)
command >filename 2> nul  Redirect output to file but suppress error
(command)>filename 2> nul  Redirect output to file but suppress CMD.exe errors
</code>```

Thanks in advance for your help.

Lionel.

答:
This will work in a batch-file run by cmd. If you are on a supported Windows system, PowerShell is available. Microsoft has been telling us for over a decade that PowerShell is the future of scripting.

If the file is not read-only or does not exist, this will write to it.

```<code>powershell -NoLogo  -NoProfile -Command ^
    if (-not (Get-ChildItem -Path .\rofile.txt -ErrorAction SilentlyContinue).IsReadOnly) ^
        { Set-Content -Path '.\rofile.txt' -Value 'then' }
</code>```

Of course, it is easier and less cryptic if it is written as a PowerShell .ps1 file script.

```<code>if (-not (Get-ChildItem -Path .\rofile.txt -ErrorAction SilentlyContinue).IsReadOnly)
    { Set-Content -Path '.\rofile.txt' -Value 'then' }
</code>```

Body:
i just subscribe here.

I would want to hide the "Acces is denied." error message in case writing to a read-only file fails. Could someone tell me why the following code doesn't work as expected ? I'm using Windows 10.

:: This file is assumed to be read-only.
echo( >"MyReadOnlyFile.txt" 2>nul
( echo( ) >"MyReadOnlyFile.txt" 2>nul

In both case the "Access is denied." message is displayed, although the following "How-to: Redirection" page at SS64 says the contrary: https://ss64.com/nt/syntax-redirection.html

Redirect to NUL (hide errors)
command >filename 2> nul  Redirect output to file but suppress error
(command)>filename 2> nul  Redirect output to file but suppress CMD.exe errors

Thanks in advance for your help.

Lionel.

Body:
This will work in a batch-file run by cmd. If you are on a supported Windows system, PowerShell is available. Microsoft has been telling us for over a decade that PowerShell is the future of scripting.

If the file is not read-only or does not exist, this will write to it.

powershell -NoLogo  -NoProfile -Command ^
    if (-not (Get-ChildItem -Path .\rofile.txt -ErrorAction SilentlyContinue).IsReadOnly) ^
        { Set-Content -Path '.\rofile.txt' -Value 'then' }

Of course, it is easier and less cryptic if it is written as a PowerShell .ps1 file script.

if (-not (Get-ChildItem -Path .\rofile.txt -ErrorAction SilentlyContinue).IsReadOnly)
    { Set-Content -Path '.\rofile.txt' -Value 'then' }


问:
How can I automatically enable notifications in selenium?
Is there anyway to use selenium to activate notifications automactically using a selenium webdriver? So far what I've learned doesn't work. Even in other stackoverflow questions.

Here is the code that I've been using

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

option = Options()
option.add_argument('--enable-notifications')

driver = webdriver.Chrome("chromedriver.exe", chrome_options=option)
driver.get("https://example.com")
```

答:
Allow Notifications

The default behavior for Chrome Browser is to ask allow or block notifications. And corresponding dialogue popup will be shown.

Notifications will be automatically allowed without showing allow/block message with the next configuration:

```<code>from selenium import webdriver
from selenium.webdriver.chrome.options import Options

option = Options()
prefs = {"profile.default_content_setting_values.notifications" : 1}
option.add_experimental_option("prefs", prefs)
driver = webdriver.Chrome("chromedriver.exe", chrome_options=option)
</code>```

For testing how it works execute the next lines:

```<code>from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

#start the driver
option = Options()
prefs = {"profile.default_content_setting_values.notifications" : 1}
option.add_experimental_option("prefs", prefs)
driver = webdriver.Chrome("chromedriver.exe", chrome_options=option)

#check the behavior on notification demo site
driver.get("https://web-push-book.gauntface.com/demos/notification-examples/")
driver.find_element(By.XPATH, "//input").click()
WebDriverWait(driver, 5).until(EC.visibility_of_element_located((By.XPATH, "//button[text()='Example Notification']"))).click()
</code>```

Dismiss Notifications

This configuration for dismiss notifications without showing allow/block message.

```<code>prefs = {"profile.default_content_setting_values.notifications" : 2}
</code>```

Body:
Allow Notifications

The default behavior for Chrome Browser is to ask allow or block notifications. And corresponding dialogue popup will be shown.

Notifications will be automatically allowed without showing allow/block message with the next configuration:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

option = Options()
prefs = {"profile.default_content_setting_values.notifications" : 1}
option.add_experimental_option("prefs", prefs)
driver = webdriver.Chrome("chromedriver.exe", chrome_options=option)

For testing how it works execute the next lines:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

#start the driver
option = Options()
prefs = {"profile.default_content_setting_values.notifications" : 1}
option.add_experimental_option("prefs", prefs)
driver = webdriver.Chrome("chromedriver.exe", chrome_options=option)

#check the behavior on notification demo site
driver.get("https://web-push-book.gauntface.com/demos/notification-examples/")
driver.find_element(By.XPATH, "//input").click()
WebDriverWait(driver, 5).until(EC.visibility_of_element_located((By.XPATH, "//button[text()='Example Notification']"))).click()

Dismiss Notifications

This configuration for dismiss notifications without showing allow/block message.

prefs = {"profile.default_content_setting_values.notifications" : 2}


问:
Java code exits after some seconds due to concurrency
I am writing the same code on tutorial. But in tutorial the program never exits, my in my computer it exits after 4 seconds. Why?
tutorial with exact time where this code is shown: https://youtu.be/vzBw1LPupnA?t=169</p>
```<code>public class Main {
    private static boolean stopRequested;

    public static void main(String[] args) throws InterruptedException {
        Thread backgroundThread = new Thread(() -> {
            int i = 0;
            while (!stopRequested) {
                i++;
                System.out.println("i = " + i);
            }
        });
        backgroundThread.start();
        TimeUnit.SECONDS.sleep(1);
        stopRequested = true;
    }
}
</code>```

答:
The reason that you are seeing different behavior on your machine and in the video is because the program has unspecified behavior.  (Or to put it another way, it is not thread-safe.)

You have two threads accessing and updating a shared variable without taking the necessary steps that will guarantee that changes made by one thread are visible to the other.  What happens in that case is not specified.

In some cases (e.g. on some platforms) the changes will be visible, either immediately or within a short time.

On others, the changes may never be visible.

In technical terms, there must be a happens-before relationship between the write by on thread and the subsequent read by the other thread.  This can be provided by both threads synchronizing on the same mutex or lock, by using a volatile variable, and in other ways.  But this code doesn't do any of those things, so there is no guarantee that the state change will be visible.

For more details, read about the Java Memory Model.

The above is sufficient to explain the difference, but there may be a more direct explanation.

In practice, something like a System.out.println can lead to changes in the visibility.  Underneath the covers, the println call will typically result in synchronization on the output stream's buffers.  That can result in a serendipitous happens-before that is sufficient to guarantee visibility.  But this behavior is not specified, so you should not rely on it.

At any rate, adding trace statements can change the behavior of multi-threaded coded.  And the fact that you (apparently) added them in your version is a second possible explanation for the difference.

The bottom line here is that a program with a memory visibility flaw is broken, but you may not be able to demonstrate that it is broken.

Body:
I am writing the same code on tutorial. But in tutorial the program never exits, my in my computer it exits after 4 seconds. Why?
tutorial with exact time where this code is shown: https://youtu.be/vzBw1LPupnA?t=169

public class Main {
    private static boolean stopRequested;

    public static void main(String[] args) throws InterruptedException {
        Thread backgroundThread = new Thread(() -> {
            int i = 0;
            while (!stopRequested) {
                i++;
                System.out.println("i = " + i);
            }
        });
        backgroundThread.start();
        TimeUnit.SECONDS.sleep(1);
        stopRequested = true;
    }
}


问:
Collections Missing with Fawn Transactions
In index.js, i create my database correctly, and i add a genre collection in the db, and is added fine.

However, when i add my rental collection, it isn't added or viewed in mongodb compass

My code for rental.js:

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

const rentalSchema =  new mongoose.Schema({
    customer: {
        type: new mongoose.Schema({
            name: {
                type: String,
                required: true,
                minlength: 2,
                maxlength: 255
             },
              phone: {
               type: String,
               required: true,
               minlength: 2,
               maxlength: 255
             },
             isGold: {
                type: Boolean,
                default: false,
                required: false
             },
        }),
        movie: {
            type: new mongoose.Schema({
                title: {
                    type: String,
                    required: true,
                    trim: true,
                    minlength: 2,
                    maxlength: 500
                },
                dailyRentalRate: {
                    type: Number,
                    min: 2,
                    required: true,
                    max: 255
                }
            }),
        },
        dateOut: {
            type: Date,
            required: true,
            default: Date.now
        },
        dateReturned: {
            type: Date
        },
        rentalFee: {
            type: Number,
            min: 0
        }
    }
})

const Rental = mongoose.model('Rental', rentalSchema)

function validate(obj) {
    const schema = {
        customerId: joi.string().required(),
        movieId: joi.string().required()
    }

    return joi.validate(obj, schema)
}

exports.Rental = Rental
exports.validate = validate
</code>```

My index.js Code (Where i initialise the database):

```<code>const mongoose = require('mongoose')
const movies = require('./routes/movies')
const rentals = require('./routes/rentals')

mongoose.connect('mongodb://localhost/vidly', { useNewUrlParser: true})
    .then(() => console.log('Connected to mongodb..'))
    .catch(() => console.error('Error connecting...'))
</code>```

This is unusual, as i do the same thing for genre, but it is added and viewed in mongodb compass!

[The image of mongo db compass is here: ]

Here is my rentals.js file, that uses rental.js for models:

```<code>const express = require('express')
const router = express.Router()
const {Customer} = require('../models/customer')
const Fawn = require('fawn')
const mongoose = require('mongoose')
const {Movie} = require('../models/movie')
const {Rental, validate} = require('../models/rental')

Fawn.init(mongoose)

router.get('/rentals', async (req, res) => {
    const rentals = await Rental.find().sort('-dateOut')
    res.send (rentals)
})

router.post('/rentals', async (req, res) => {
    const {error} = validate(req.body)
    if (error) return res.status(400).send('Error')

    // Makes sure the customerId/customer sends us is valid
    const customer = await Customer.findById(req.body.customerId)
    if (!customer) return res.status(404).send('Invalid customerId')

    const movie = await Movie.findById(req.body.movieId)
    if (!movie) return res.status(404).send('Invalid movieId')

    let rental = new Rental({
        customer: {
            _id: customer._id,
            name: customer.name,
            phone: customer.phone
        },
        movie: {
            _id: movie._id,
            title: movie.title,
            dailyRentalRate: movie.dailyRentalRate
        }
    })

    // This is for our success scenario
    try {
            // All args in here treated all together as unit
             new Fawn.Task()
                // First arg is collection we work with, and second is obj we wanna save
                .save('rentals', rental)
                // Update movies collection Second Arg is movie that should be updated Third is we increment the numInstock prop, and decrement by 1
                .update('movies', { _id: movie._id}, {
                $inc: { numberInStock: -1}
                })
                .run()
             res.send(rental)
    }
    catch(ex) {
       // 500 means Internal server error
       res.status(500).send('Something failed.')
    }
})

module.exports = router
</code>```

Here is mongodb compass, and the collections seen

答:
Instead of using

```<code>Fawn.init(mongoose)
</code>```

try using

```<code>Fawn.init('mongodb://localhost/yourDataBaseName')
</code>```

Body:
In index.js, i create my database correctly, and i add a genre collection in the db, and is added fine.

However, when i add my rental collection, it isn't added or viewed in mongodb compass

My code for rental.js:

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

const rentalSchema =  new mongoose.Schema({
    customer: {
        type: new mongoose.Schema({
            name: {
                type: String,
                required: true,
                minlength: 2,
                maxlength: 255
             },
              phone: {
               type: String,
               required: true,
               minlength: 2,
               maxlength: 255
             },
             isGold: {
                type: Boolean,
                default: false,
                required: false
             },
        }),
        movie: {
            type: new mongoose.Schema({
                title: {
                    type: String,
                    required: true,
                    trim: true,
                    minlength: 2,
                    maxlength: 500
                },
                dailyRentalRate: {
                    type: Number,
                    min: 2,
                    required: true,
                    max: 255
                }
            }),
        },
        dateOut: {
            type: Date,
            required: true,
            default: Date.now
        },
        dateReturned: {
            type: Date
        },
        rentalFee: {
            type: Number,
            min: 0
        }
    }
})

const Rental = mongoose.model('Rental', rentalSchema)

function validate(obj) {
    const schema = {
        customerId: joi.string().required(),
        movieId: joi.string().required()
    }

    return joi.validate(obj, schema)
}

exports.Rental = Rental
exports.validate = validate

My index.js Code (Where i initialise the database):

const mongoose = require('mongoose')
const movies = require('./routes/movies')
const rentals = require('./routes/rentals')

mongoose.connect('mongodb://localhost/vidly', { useNewUrlParser: true})
    .then(() => console.log('Connected to mongodb..'))
    .catch(() => console.error('Error connecting...'))

This is unusual, as i do the same thing for genre, but it is added and viewed in mongodb compass!

[The image of mongo db compass is here: ]

Here is my rentals.js file, that uses rental.js for models:

const express = require('express')
const router = express.Router()
const {Customer} = require('../models/customer')
const Fawn = require('fawn')
const mongoose = require('mongoose')
const {Movie} = require('../models/movie')
const {Rental, validate} = require('../models/rental')

Fawn.init(mongoose)

router.get('/rentals', async (req, res) => {
    const rentals = await Rental.find().sort('-dateOut')
    res.send (rentals)
})

router.post('/rentals', async (req, res) => {
    const {error} = validate(req.body)
    if (error) return res.status(400).send('Error')

    // Makes sure the customerId/customer sends us is valid
    const customer = await Customer.findById(req.body.customerId)
    if (!customer) return res.status(404).send('Invalid customerId')

    const movie = await Movie.findById(req.body.movieId)
    if (!movie) return res.status(404).send('Invalid movieId')

    let rental = new Rental({
        customer: {
            _id: customer._id,
            name: customer.name,
            phone: customer.phone
        },
        movie: {
            _id: movie._id,
            title: movie.title,
            dailyRentalRate: movie.dailyRentalRate
        }
    })

    // This is for our success scenario
    try {
            // All args in here treated all together as unit
             new Fawn.Task()
                // First arg is collection we work with, and second is obj we wanna save
                .save('rentals', rental)
                // Update movies collection Second Arg is movie that should be updated Third is we increment the numInstock prop, and decrement by 1
                .update('movies', { _id: movie._id}, {
                $inc: { numberInStock: -1}
                })
                .run()
             res.send(rental)
    }
    catch(ex) {
       // 500 means Internal server error
       res.status(500).send('Something failed.')
    }
})

module.exports = router

Here is mongodb compass, and the collections seen

Body:
Instead of using

Fawn.init(mongoose)

try using

Fawn.init('mongodb://localhost/yourDataBaseName')


问:
Trigger, which logs/deletes a row into a separate table, before an entry with the same attribute value is inserted
I have two tables which both have the same columns and a foreign key named id. Table t1 is supposed to store the current data while table t2 is a log table.

The rows in table t1 are supposed to be unique, so I want to create a trigger which copies the data from t1 to t2 and then removes the entries in t1 (if I insert data with an id which is already found in t1).

If the id is not found in t1, the trigger is simply supposed to insert the data into t1 and do nothing with t2. I am using PostgreSQL and this is my current attempt but it doesn't seem to work:

```<code>CREATE OR REPLACE FUNCTION move_data_to_historical_measured_data_insert()
    RETURNS TRIGGER
    LANGUAGE PLPGSQL
    AS
$$
BEGIN
    IF OLD.id = NEW.id THEN
        INSERT INTO t2(id, value, timestamp)
        VALUES(OLD.id, OLD.value, OLD.timestamp);
        DELETE FROM t1;
        RETURN NULL;
    ELSE
        RETURN NULL;
    END IF;
END;
$$

CREATE OR REPLACE TRIGGER store_data_to_history_insert
    BEFORE INSERT
    ON t1
    FOR EACH ROW
    EXECUTE PROCEDURE move_data_to_historical_measured_data_insert();

</code>```

答:
```<code>CREATE OR REPLACE FUNCTION move_data_to_historical_measured_data_insert()
RETURNS trigger
LANGUAGE plpgsql
AS $function$
begin

    if (exists(select t1.id from t1 where t1.id = new.id)) then

        insert into t2 (id, value, timestamp)
        select t1.id, t1.value, t1.timestamp from t1 where t1.id = new.id;

        delete from t1 where t1.id = new.id;

    end if;

    return new;
END;
$function$
;

CREATE OR REPLACE TRIGGER store_data_to_history_insert
    BEFORE INSERT
    ON t1
    FOR EACH ROW
    EXECUTE PROCEDURE move_data_to_historical_measured_data_insert();
</code>```

Body:
I have two tables which both have the same columns and a foreign key named id. Table t1 is supposed to store the current data while table t2 is a log table.

The rows in table t1 are supposed to be unique, so I want to create a trigger which copies the data from t1 to t2 and then removes the entries in t1 (if I insert data with an id which is already found in t1).

If the id is not found in t1, the trigger is simply supposed to insert the data into t1 and do nothing with t2. I am using PostgreSQL and this is my current attempt but it doesn't seem to work:

CREATE OR REPLACE FUNCTION move_data_to_historical_measured_data_insert()
    RETURNS TRIGGER
    LANGUAGE PLPGSQL
    AS
$$
BEGIN
    IF OLD.id = NEW.id THEN
        INSERT INTO t2(id, value, timestamp)
        VALUES(OLD.id, OLD.value, OLD.timestamp);
        DELETE FROM t1;
        RETURN NULL;
    ELSE
        RETURN NULL;
    END IF;
END;
$$

CREATE OR REPLACE TRIGGER store_data_to_history_insert
    BEFORE INSERT
    ON t1
    FOR EACH ROW
    EXECUTE PROCEDURE move_data_to_historical_measured_data_insert();


问:
Argument values change on run time in JavaScript
Please consider the below code:

function func1(a, b) {
  let args = arguments;
  console.log(args);

  return function() {
    for (let i in args) {
      console.log(args[i], a, b)
      args[i] += (a + b);
      console.log("|")
      console.log(args[i], a, b);
      console.log("end")
    }
  }
}

func1(2, 4)();```
</div>
</div>
</p>
<p>This give the below output</p>
<pre class="lang-none prettyprint-override"><code>2 2 4
|
8 8 4
end
4 8 4
|
16 8 16
end
</code>```

How does the value of a, b change here?

答:
In loose mode,¹ the arguments pseudo-array has a live link to the formal parameters of a function. Here's a simpler example:

function example(a) {
    console.log("before, a = " + a);
    ++arguments[0];
    console.log("after, a = " + a);
}

example(1);```
</div>
</div>
</p>
<p>As you can see, <code>++arguments[0]</code> <strong>modified the value of <code>a</code></strong>.</p>
<p>This spooky link is removed in strict mode, which should be used by all new code (explicitly, or by using modules):</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>"use strict";
function example(a) {
    console.log("before, a = " + a);
    ++arguments[0];
    console.log("after, a = " + a);
}

example(1);</code>```

In a comment, you've asked:

So even though if we clone the arguments, it still have live link to its clone?

Nothing in the code in the question clones the arguments object. let args = arguments; just points args at the object, it doesn't copy it. You start out with:

```
                +−−−−−−−−−−−−−−−−−−−−−−−−−−+
arguments:−−−−−>|    (arguments object)    |
                +−−−−−−−−−−−−−−−−−−−−−−−−−−+
                |   (spooky link to a, b)  |
                +−−−−−−−−−−−−−−−−−−−−−−−−−−+
```

Then let args = arguments; just does this:

```

arguments:−−+
            |
            |   +−−−−−−−−−−−−−−−−−−−−−−−−−−+
            +−−>|    (arguments object)    |
            |   +−−−−−−−−−−−−−−−−−−−−−−−−−−+
            |   |   (spooky link to a, b)  |
args:−−−−−−−+   +−−−−−−−−−−−−−−−−−−−−−−−−−−+

```

It's still the same object.

If you copy it (just a shallow copy is fine), then you can modify the copy without affecting a and b:

```<code>let args = [...arguments]; // Or `= Array.prototype.slice.call(arguments);`
</code>```

Then you get:

```
                +−−−−−−−−−−−−−−−−−−−−−−−−−−+
arguments:−−−−−>|    (arguments object)    |
                +−−−−−−−−−−−−−−−−−−−−−−−−−−+
                |   (spooky link to a, b)  |
                +−−−−−−−−−−−−−−−−−−−−−−−−−−+

                +−−−−−−−−−−−−−−−−−−−−−−−−−−+
argss:−−−−−−−−−>|          (array)         |
                +−−−−−−−−−−−−−−−−−−−−−−−−−−+
                | 0: value copied from `a` |
                | 1: value copied from `b` |
                +−−−−−−−−−−−−−−−−−−−−−−−−−−+
```

...and changes to args don't show in a and b.

¹ loose mode is often, sadly, called "sloppy" mode

Body:
Please consider the below code:

function func1(a, b) {
  let args = arguments;
  console.log(args);

  return function() {
    for (let i in args) {
      console.log(args[i], a, b)
      args[i] += (a + b);
      console.log("|")
      console.log(args[i], a, b);
      console.log("end")
    }
  }
}

func1(2, 4)();

This give the below output

2 2 4
|
8 8 4
end
4 8 4
|
16 8 16
end

How does the value of a, b change here?

Body:
In loose mode,¹ the arguments pseudo-array has a live link to the formal parameters of a function. Here's a simpler example:

function example(a) {
    console.log("before, a = " + a);
    ++arguments[0];
    console.log("after, a = " + a);
}

example(1);

As you can see, ++arguments[0] modified the value of a.

This spooky link is removed in strict mode, which should be used by all new code (explicitly, or by using modules):

"use strict";
function example(a) {
    console.log("before, a = " + a);
    ++arguments[0];
    console.log("after, a = " + a);
}

example(1);

In a comment, you've asked:

So even though if we clone the arguments, it still have live link to its clone?

Nothing in the code in the question clones the arguments object. let args = arguments; just points args at the object, it doesn't copy it. You start out with:

                +−−−−−−−−−−−−−−−−−−−−−−−−−−+
arguments:−−−−−>|    (arguments object)    |
                +−−−−−−−−−−−−−−−−−−−−−−−−−−+
                |   (spooky link to a, b)  |
                +−−−−−−−−−−−−−−−−−−−−−−−−−−+

Then let args = arguments; just does this:

arguments:−−+
            |
            |   +−−−−−−−−−−−−−−−−−−−−−−−−−−+
            +−−>|    (arguments object)    |
            |   +−−−−−−−−−−−−−−−−−−−−−−−−−−+
            |   |   (spooky link to a, b)  |
args:−−−−−−−+   +−−−−−−−−−−−−−−−−−−−−−−−−−−+

It's still the same object.

If you copy it (just a shallow copy is fine), then you can modify the copy without affecting a and b:

let args = [...arguments]; // Or `= Array.prototype.slice.call(arguments);`

Then you get:

                +−−−−−−−−−−−−−−−−−−−−−−−−−−+
arguments:−−−−−>|    (arguments object)    |
                +−−−−−−−−−−−−−−−−−−−−−−−−−−+
                |   (spooky link to a, b)  |
                +−−−−−−−−−−−−−−−−−−−−−−−−−−+

                +−−−−−−−−−−−−−−−−−−−−−−−−−−+
argss:−−−−−−−−−>|          (array)         |
                +−−−−−−−−−−−−−−−−−−−−−−−−−−+
                | 0: value copied from `a` |
                | 1: value copied from `b` |
                +−−−−−−−−−−−−−−−−−−−−−−−−−−+

...and changes to args don't show in a and b.

¹ loose mode is often, sadly, called "sloppy" mode


问:
Next JS build failing due to ''Export encountered errors on following paths"
I am encountering this build error when I deploy my next js site to vercel

```<code>15:02:38    > Build error occurred
15:02:38    Error: Export encountered errors on following paths:
15:02:38        /about/undefined
15:02:38        at exportApp (/vercel/workpath0/node_modules/next/dist/export/index.js:30:1103)
15:02:38        at processTicksAndRejections (internal/process/task_queues.js:97:5)
15:02:38        at async /vercel/workpath0/node_modules/next/dist/build/index.js:39:69
15:02:38        at async /vercel/workpath0/node_modules/next/dist/build/tracer.js:1:525
</code>```

My website does not have a page called about, so I really don't know what this error is referring to. I checked as much as I could to find a reliable answer, but couldn't. Any help is appreciated!

答: In my case this happened when backend API was down. So you need to wait till backend API will reset and try again</p>

Body:
I am encountering this build error when I deploy my next js site to vercel

15:02:38    > Build error occurred
15:02:38    Error: Export encountered errors on following paths:
15:02:38        /about/undefined
15:02:38        at exportApp (/vercel/workpath0/node_modules/next/dist/export/index.js:30:1103)
15:02:38        at processTicksAndRejections (internal/process/task_queues.js:97:5)
15:02:38        at async /vercel/workpath0/node_modules/next/dist/build/index.js:39:69
15:02:38        at async /vercel/workpath0/node_modules/next/dist/build/tracer.js:1:525

My website does not have a page called about, so I really don't know what this error is referring to. I checked as much as I could to find a reliable answer, but couldn't. Any help is appreciated!


问:
PHP Websocket Server hybi10
So Chrome 14 has implemented hybi10 version of websockets. I have a in house program that our company uses via chrome that uses websockets which is broken with this change.

Has anyone been successful framing the data using a php server? I am able to get the new handshake to work but I can't seem to figure out the framing. There is a python example here https://github.com/kanaka/websockify/blob/master/websocket.py#L233 but I am having a difficult time converting this to php, anyone have a suggestion?

I should mention that the function in question on the python example is decode_hybi().

答:
This code assumes no errors or malformed frames and is based on this answer - How to (de)construct data frames in WebSockets hybi 08+?.

This code is very basic and is far from a complete solution. It works for my purposes (which are pretty basic). Hopefully it is of use to others.

```<code>function handle_data($data){
    $bytes = $data;
    $data_length = "";
    $mask = "";
    $coded_data = "" ;
    $decoded_data = "";
    $data_length = $bytes[1] & 127;
    if($data_length === 126){
       $mask = substr($bytes, 4, 8);
       $coded_data = substr($bytes, 8);
    }else if($data_length === 127){
        $mask = substr($bytes, 10, 14);
        $coded_data = substr($bytes, 14);
    }else{
        $mask = substr($bytes, 2, 6);
        $coded_data = substr($bytes, 6);
    }
    for($i=0;$i<strlen($coded_data);$i++){
        $decoded_data .= $coded_data[$i] ^ $mask[$i%4];
    }
    $this->log("Server Received->".$decoded_data);
    return true;
}
</code>```

Here is the code to send data back. Again this is pretty basic, it assumes you are sending a single text frame. No continuation frames etc. No error checking either. Hopefully others find it useful.

```<code>public function send($data)
{
    $frame = Array();
    $encoded = "";
    $frame[0] = 0x81;
    $data_length = strlen($data);

    if($data_length <= 125){
        $frame[1] = $data_length;
    }else{
        $frame[1] = 126;
        $frame[2] = $data_length >> 8;
        $frame[3] = $data_length & 0xFF;
    }

    for($i=0;$i<sizeof($frame);$i++){
        $encoded .= chr($frame[$i]);
    }

    $encoded .= $data;
    write_to_socket($this->socket, $encoded);
    return true;
}
</code>```

Title: PHP Websocket Server hybi10

Body:
This code assumes no errors or malformed frames and is based on this answer - How to (de)construct data frames in WebSockets hybi 08+?.

This code is very basic and is far from a complete solution. It works for my purposes (which are pretty basic). Hopefully it is of use to others.

function handle_data($data){
    $bytes = $data;
    $data_length = "";
    $mask = "";
    $coded_data = "" ;
    $decoded_data = "";
    $data_length = $bytes[1] & 127;
    if($data_length === 126){
       $mask = substr($bytes, 4, 8);
       $coded_data = substr($bytes, 8);
    }else if($data_length === 127){
        $mask = substr($bytes, 10, 14);
        $coded_data = substr($bytes, 14);
    }else{
        $mask = substr($bytes, 2, 6);
        $coded_data = substr($bytes, 6);
    }
    for($i=0;$i<strlen($coded_data);$i++){
        $decoded_data .= $coded_data[$i] ^ $mask[$i%4];
    }
    $this->log("Server Received->".$decoded_data);
    return true;
}

Here is the code to send data back. Again this is pretty basic, it assumes you are sending a single text frame. No continuation frames etc. No error checking either. Hopefully others find it useful.

public function send($data)
{
    $frame = Array();
    $encoded = "";
    $frame[0] = 0x81;
    $data_length = strlen($data);

    if($data_length <= 125){
        $frame[1] = $data_length;
    }else{
        $frame[1] = 126;
        $frame[2] = $data_length >> 8;
        $frame[3] = $data_length & 0xFF;
    }

    for($i=0;$i<sizeof($frame);$i++){
        $encoded .= chr($frame[$i]);
    }

    $encoded .= $data;
    write_to_socket($this->socket, $encoded);
    return true;
}


问:
nested array object property return undefined typeError in react redux
i want to show the post detail in frontend. my api is showing the postdetail like below captured in postman:

```<code>"message": "Posts fetched successfully!",
    "posts": {
        "_id": "61f05f676793d49f466e7aaa",
        "title": "Liberal Arts Student Sample",
        "content": "The three-page.",
        "creator": {
            "_id": "61cd99efa0b8d616a7a53ce1",
            "createdAt": "2021-12-30T11:37:19.041Z",
            "updatedAt": "2022-01-06T14:35:48.801Z",
            "__v": 0,
            "bio": "user bio",
            "name": "username"
        },
        "Comments": [],
        "created": "2022-01-25T20:36:55.095Z",
        "createdAt": "2022-01-25T20:36:55.096Z",
        "updatedAt": "2022-01-25T20:36:55.096Z",
        "__v": 0
    }
}
</code>```

i want to exhibit this post detail in frontend and here is the code:

```<code>export default function PostDetail() {
    const { postId } = useParams();
    const post = useSelector((state) => state.post)
    const dispatch = useDispatch();
    const { title, content,creator, created } = post;
    const fetchPostDetail = async (id) => {
        const response = await axios.get(`http://localhost:5000/api/articles/post/${id}`, { post })
            .catch(err => {
                console.log(err);
            })
        dispatch(selectedPost(response.data.posts));
              }

    useEffect(() => {
        fetchPostDetail(postId)
    }, [])

    return (
        <div>
            <h1>Post Detail</h1>
            <div>
                <h2>{title}</h2>
                <i>posted in {created}</i>
                 <li>Created by {creator.map((m,i)=>(
<b key={i}>{m.name}</b>
                 ))}</li>
                <p>{content}</p>
            </div>
        </div>
    );
}
</code>```

There are three errors:

Uncaught TypeError: creator is undefined

The above error occurred in the  component:

Uncaught TypeError: creator is undefined

if i mute the

Created by {creator.map((m,i)=>(
{m.name}
                 ))}
 then it shows the post detail without post author name. but i want to show the author name.

how can i solve that?
thank you in advance

答:
Here, creator is an Object. Whereas .map function is for Array.
To map an Object you can check:
map function for objects (instead of arrays)</p>

Body:
i want to show the post detail in frontend. my api is showing the postdetail like below captured in postman:

"message": "Posts fetched successfully!",
    "posts": {
        "_id": "61f05f676793d49f466e7aaa",
        "title": "Liberal Arts Student Sample",
        "content": "The three-page.",
        "creator": {
            "_id": "61cd99efa0b8d616a7a53ce1",
            "createdAt": "2021-12-30T11:37:19.041Z",
            "updatedAt": "2022-01-06T14:35:48.801Z",
            "__v": 0,
            "bio": "user bio",
            "name": "username"
        },
        "Comments": [],
        "created": "2022-01-25T20:36:55.095Z",
        "createdAt": "2022-01-25T20:36:55.096Z",
        "updatedAt": "2022-01-25T20:36:55.096Z",
        "__v": 0
    }
}

i want to exhibit this post detail in frontend and here is the code:

export default function PostDetail() {
    const { postId } = useParams();
    const post = useSelector((state) => state.post)
    const dispatch = useDispatch();
    const { title, content,creator, created } = post;
    const fetchPostDetail = async (id) => {
        const response = await axios.get(`http://localhost:5000/api/articles/post/${id}`, { post })
            .catch(err => {
                console.log(err);
            })
        dispatch(selectedPost(response.data.posts));
              }

    useEffect(() => {
        fetchPostDetail(postId)
    }, [])

    return (

Post Detail

{title}

                posted in {created}

Created by {creator.map((m,i)=>(
{m.name}
                 ))}

{content}

    );
}

There are three errors:

Uncaught TypeError: creator is undefined

The above error occurred in the  component:

Uncaught TypeError: creator is undefined

if i mute the

Created by {creator.map((m,i)=>(
{m.name}
                 ))}
 then it shows the post detail without post author name. but i want to show the author name.

how can i solve that?
thank you in advance


问:
Is there a way to get corresponding index value in a 2nd array using the 1st array as a reference in Javascript?
I am very new to algorithm and programming in general. I may require more explanation than an average fellow. Apologies in advance.

My aim is to Create a function that returns a number, based on the string provided. I have been told that this can be done using loops. I believe my errors lies in the if statement. However, cant seem to figure it out. I would be glad if somebody could help.

```<code>function word(s) {
  let str = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "zero"];
  let int = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];

  for (let j = 0; j < int.length; j++) {
    for (let i = 0; i < str.length; i++) {
      if (s === str[i]) {
        return int[j]
      }
    }
  }
}
</code>```

答:
You need only a single loop to find the index of the given word. If found return the value form the other array by using the actual index.

```<code>for (let i = 0; i < str.length; i++){
    if (s === str[i]) return int[i];
}
</code>```

A short approach could use Array#lastIndexOf.

Body:
I am very new to algorithm and programming in general. I may require more explanation than an average fellow. Apologies in advance.

My aim is to Create a function that returns a number, based on the string provided. I have been told that this can be done using loops. I believe my errors lies in the if statement. However, cant seem to figure it out. I would be glad if somebody could help.

function word(s) {
  let str = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "zero"];
  let int = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];

  for (let j = 0; j < int.length; j++) {
    for (let i = 0; i < str.length; i++) {
      if (s === str[i]) {
        return int[j]
      }
    }
  }
}

Body:
You need only a single loop to find the index of the given word. If found return the value form the other array by using the actual index.

for (let i = 0; i < str.length; i++){
    if (s === str[i]) return int[i];
}

A short approach could use Array#lastIndexOf.