问:
What is the correct way to run a Flask application with Nginx and uWSGI in a reverse proxy case?
I am a beginner and I am going to run my first Flask application. I have to deploy a Flask application with Nginx and uWSGI. The application is running on uWSGI but not in Nginx. I will reguest you to please see all the attempts I have mentioned below.The code is as follows:

Attempt 1

api.py

```<code>from flask import Flask, request, make_response

app = Flask(__name__)
app.secret_key = "Thisisyoursecret"

# Create a simple endpoint /Hello with return message "Welcome to your flask application"

@app.route('/Hello')
def hello():
  res=make_response("Welcome to your flask application")
  return res

  if __name__ == "__main__":
    app.run(host='0.0.0.0')
</code>```

wsgi.py

```<code>from api import app
if __name__ == "__main__":
    app.run()
</code>```

deploy.conf (I was instructed to put this in Virtual Host Config of nginx.conf)

```<code> server {
        listen 8000;

location / {
  include uwsgi_params;
  uwsgi_pass 127.0.0.1:8081;

}

location /Hello {
    alias /project/challenges/api.py;  (I doubt this)
}
</code>```

}
uwsgi.ini

```<code>[uwsgi]
module = wsgi:app

master = true
processes = 5
</code>```

The test code given in the question for testing my code is as follows: tests.py

```<code>import os

import pytest
import requests
from .api import app

class Test_API:

client = app.test_client()

def test_hello_from_app(self):
    url = "/Hello"
    response = self.client.get(url)
    assert response.status_code == 200
    assert response.data == b'Welcome to your flask application'

def test_hello_from_app_on_port(self):
    url = "http://localhost:8081/Hello"
    response = requests.get(url)
    assert response.status_code == 200
    assert response.text == 'Welcome to your flask application'

def test_hello_from_nginx_server(self):
    url = "http://localhost:8000/Hello"
    response = requests.get(url)
    assert response.status_code == 200
    assert response.text == 'Welcome to your flask application'

def test_conf_file_contents(self):
    with open('deploy.conf', 'r') as f:
        content = f.read()
        assert "location /Hello" in content
        assert "server localhost:8081" in content
        assert "listen 8000" in content
</code>```

the errors are: (404 status)

```<code>=================================== short test summary info ====================================
FAILED tests.py::Test_API::test_hello_from_nginx_server - assert 404 == 200
FAILED tests.py::Test_API::test_conf_file_contents - AssertionError: assert 'server localhost...
</code>```

I am not allowed to edit the tests.py file. Its already written and read only.

I doubt the location /Hello{} block in deploy.conf.

The directory structure is:

```<code>projects
   |__challenge
        |_ __init__.py
        |__api.py
        |__deploy.conf
        |__wsgi.py
        |__uwsgi.ini
        |__ tests.py
</code>```

Attempt 2:

deploy.conf:

```<code>server {
    listen 8000;
server_name localhost:8081;

location / {
  include uwsgi_params;
  uwsgi_pass 127.0.0.1:8081;

}

location /Hello/ {
    alias /project/challenges/api.py;
}
}
</code>```

Kept rest same.

Got same errors

the errors are: (404 status)

```<code>=================================== short test summary info ====================================
FAILED tests.py::Test_API::test_hello_from_nginx_server - assert 404 == 200
FAILED tests.py::Test_API::test_conf_file_contents - AssertionError: assert 'server localhost...
</code>```

Attempt 3:

deploy.conf:

server {
listen 8000;

```<code>location / {
  include uwsgi_params;
  uwsgi_pass 127.0.0.1:8081;

}

location /Hello/ {
    alias http://localhost:8000/Hello/;
}
}
</code>```

Kept rest same.

the errors are: (502 status)

```<code>=================================== short test summary info ====================================
FAILED tests.py::Test_API::test_hello_from_nginx_server - assert 502 == 200
FAILED tests.py::Test_API::test_conf_file_contents - AssertionError: assert 'server localhost...
</code>```

Attempt 4:

deploy.conf:

```<code>server {
    listen 8000;
    server_name localhost:8081;

    location / {
      include uwsgi_params;
      uwsgi_pass 127.0.0.1:8081;

    }

    location /Hello/ {
        alias http://localhost:8000/Hello/;
    }
}
</code>```

Kept rest same.

Got same error.

the errors are: (502 status)

```<code>=================================== short test summary info ====================================
FAILED tests.py::Test_API::test_hello_from_nginx_server - assert 502 == 200
FAILED tests.py::Test_API::test_conf_file_contents - AssertionError: assert 'server localhost...
In all the cases 1 error was common i.e Assertion error of "server localhost:8081".
</code>```

I mentioned the test.py file which is actually testing my code, above. This file is already provided with question and I am not supposed to edit it.

Nginx server is starting fine. But I get those errors.

I suspect the location /Hello{} block.

Kindly suggest me what to do.

Attempt 5

deploy.conf :

```<code>server {
        listen 8000;

location /Hello {
  include uwsgi_params;
  uwsgi_pass 127.0.0.1:8081;

}
}
</code>```

uwsgi.ini

```<code>[uwsgi]
socket = 127.0.0.1:8081
module = wsgi:app

master = true
processes = 5
</code>```

Error:

```<code>FAILED tests.py::Test_API::test_hello_from_nginx_server - assert 502 == 200
FAILED tests.py::Test_API::test_conf_file_contents - AssertionError: assert 'server localhost:8081'..
</code>```

Attempt 6

deploy.conf

```<code>server {
listen 8000;
location / {
  include uwsgi_params;
  uwsgi_pass 127.0.0.1:8081;
}
location /Hello {
    alias http://localhost:8000;
}

}
</code>```

uwsgi.ini

```<code>[uwsgi]
socket = 127.0.0.1:8081
module = wsgi:app

master = true
processes = 5
</code>```

Error:

```<code>====================================== short test summary info =======================================
FAILED tests.py::Test_API::test_hello_from_nginx_server - assert 404 == 200
FAILED tests.py::Test_API::test_conf_file_contents - AssertionError: assert 'server localhost:8081'..
</code>```

答:
This can be done in another way.

Do the following changes in deploy.conf as below:

```<code>server {
    listen 8000;
    server localhost:8081

    location /Hello {
        alias /projects/challenge/api;
    }
}
</code>```

Add the deploy.conf in nginx.conf.

Then click on Run. It will start the gunicorn server with this command:

```<code>export FLASK_APP=api; export FLASK_ENV=development;gunicorn --bind 0.0.0.0:8081 wsgi:app
</code>```

Now manually open another terminal and run the following command:

```<code>export FLASK_APP=api; export FLASK_ENV=development;gunicorn --bind 0.0.0.0:8000 wsgi:app
</code>```

Now your test cases might pass, I think. Try and let me know,if this works or not.

Body:
I am a beginner and I am going to run my first Flask application. I have to deploy a Flask application with Nginx and uWSGI. The application is running on uWSGI but not in Nginx. I will reguest you to please see all the attempts I have mentioned below.The code is as follows:

Attempt 1

api.py

from flask import Flask, request, make_response

app = Flask(__name__)
app.secret_key = "Thisisyoursecret"

# Create a simple endpoint /Hello with return message "Welcome to your flask application"

@app.route('/Hello')
def hello():
  res=make_response("Welcome to your flask application")
  return res

  if __name__ == "__main__":
    app.run(host='0.0.0.0')

wsgi.py

from api import app
if __name__ == "__main__":
    app.run()

deploy.conf (I was instructed to put this in Virtual Host Config of nginx.conf)

 server {
        listen 8000;

location / {
  include uwsgi_params;
  uwsgi_pass 127.0.0.1:8081;

}

location /Hello {
    alias /project/challenges/api.py;  (I doubt this)
}

}
uwsgi.ini

[uwsgi]
module = wsgi:app

master = true
processes = 5

The test code given in the question for testing my code is as follows: tests.py

import os

import pytest
import requests
from .api import app

class Test_API:

client = app.test_client()

def test_hello_from_app(self):
    url = "/Hello"
    response = self.client.get(url)
    assert response.status_code == 200
    assert response.data == b'Welcome to your flask application'

def test_hello_from_app_on_port(self):
    url = "http://localhost:8081/Hello"
    response = requests.get(url)
    assert response.status_code == 200
    assert response.text == 'Welcome to your flask application'

def test_hello_from_nginx_server(self):
    url = "http://localhost:8000/Hello"
    response = requests.get(url)
    assert response.status_code == 200
    assert response.text == 'Welcome to your flask application'

def test_conf_file_contents(self):
    with open('deploy.conf', 'r') as f:
        content = f.read()
        assert "location /Hello" in content
        assert "server localhost:8081" in content
        assert "listen 8000" in content

the errors are: (404 status)

=================================== short test summary info ====================================
FAILED tests.py::Test_API::test_hello_from_nginx_server - assert 404 == 200
FAILED tests.py::Test_API::test_conf_file_contents - AssertionError: assert 'server localhost...

I am not allowed to edit the tests.py file. Its already written and read only.

I doubt the location /Hello{} block in deploy.conf.

The directory structure is:

projects
   |__challenge
        |_ __init__.py
        |__api.py
        |__deploy.conf
        |__wsgi.py
        |__uwsgi.ini
        |__ tests.py

Attempt 2:

deploy.conf:

server {
    listen 8000;
server_name localhost:8081;

location / {
  include uwsgi_params;
  uwsgi_pass 127.0.0.1:8081;

}

location /Hello/ {
    alias /project/challenges/api.py;
}
}

Kept rest same.

Got same errors

the errors are: (404 status)

=================================== short test summary info ====================================
FAILED tests.py::Test_API::test_hello_from_nginx_server - assert 404 == 200
FAILED tests.py::Test_API::test_conf_file_contents - AssertionError: assert 'server localhost...

Attempt 3:

deploy.conf:

server {
listen 8000;

location / {
  include uwsgi_params;
  uwsgi_pass 127.0.0.1:8081;

}

location /Hello/ {
    alias http://localhost:8000/Hello/;
}
}

Kept rest same.

the errors are: (502 status)

=================================== short test summary info ====================================
FAILED tests.py::Test_API::test_hello_from_nginx_server - assert 502 == 200
FAILED tests.py::Test_API::test_conf_file_contents - AssertionError: assert 'server localhost...

Attempt 4:

deploy.conf:

server {
    listen 8000;
    server_name localhost:8081;

    location / {
      include uwsgi_params;
      uwsgi_pass 127.0.0.1:8081;

    }

    location /Hello/ {
        alias http://localhost:8000/Hello/;
    }
}

Kept rest same.

Got same error.

the errors are: (502 status)

=================================== short test summary info ====================================
FAILED tests.py::Test_API::test_hello_from_nginx_server - assert 502 == 200
FAILED tests.py::Test_API::test_conf_file_contents - AssertionError: assert 'server localhost...
In all the cases 1 error was common i.e Assertion error of "server localhost:8081".

I mentioned the test.py file which is actually testing my code, above. This file is already provided with question and I am not supposed to edit it.

Nginx server is starting fine. But I get those errors.

I suspect the location /Hello{} block.

Kindly suggest me what to do.

Attempt 5

deploy.conf :

server {
        listen 8000;

location /Hello {
  include uwsgi_params;
  uwsgi_pass 127.0.0.1:8081;

}
}

uwsgi.ini

[uwsgi]
socket = 127.0.0.1:8081
module = wsgi:app

master = true
processes = 5

Error:

FAILED tests.py::Test_API::test_hello_from_nginx_server - assert 502 == 200
FAILED tests.py::Test_API::test_conf_file_contents - AssertionError: assert 'server localhost:8081'..

Attempt 6

deploy.conf

server {
listen 8000;
location / {
  include uwsgi_params;
  uwsgi_pass 127.0.0.1:8081;
}
location /Hello {
    alias http://localhost:8000;
}

}

uwsgi.ini

[uwsgi]
socket = 127.0.0.1:8081
module = wsgi:app

master = true
processes = 5

Error:

====================================== short test summary info =======================================
FAILED tests.py::Test_API::test_hello_from_nginx_server - assert 404 == 200
FAILED tests.py::Test_API::test_conf_file_contents - AssertionError: assert 'server localhost:8081'..

Body:
This can be done in another way.

Do the following changes in deploy.conf as below:

server {
    listen 8000;
    server localhost:8081

    location /Hello {
        alias /projects/challenge/api;
    }
}

Add the deploy.conf in nginx.conf.

Then click on Run. It will start the gunicorn server with this command:

export FLASK_APP=api; export FLASK_ENV=development;gunicorn --bind 0.0.0.0:8081 wsgi:app

Now manually open another terminal and run the following command:

export FLASK_APP=api; export FLASK_ENV=development;gunicorn --bind 0.0.0.0:8000 wsgi:app

Now your test cases might pass, I think. Try and let me know,if this works or not.


来源: stackexchange

问:
cocoapods not installing
What does it mean and how can I fix it:</p>

```<code>pod install
/Library/Ruby/Site/2.0.0/rubygems.rb:250:in `find_spec_for_exe': can't find gem cocoapods (>= 0.a) (Gem::GemNotFoundException)
from /Library/Ruby/Site/2.0.0/rubygems.rb:278:in `activate_bin_path'
from /usr/local/bin/pod:22:in `<main>'
</code>```

答:
I'd installed Cocoapods using gem, so I reinstalled it again using gem. nothing happened.
so I removed it and install it using brew. it works.</p>

ContentLicense: CC BY-SA 3.0

Title: cocoapods not installing

Body:
What does it mean and how can I fix it:

pod install
/Library/Ruby/Site/2.0.0/rubygems.rb:250:in `find_spec_for_exe': can't find gem cocoapods (>= 0.a) (Gem::GemNotFoundException)
from /Library/Ruby/Site/2.0.0/rubygems.rb:278:in `activate_bin_path'
from /usr/local/bin/pod:22:in `'

ContentLicense: CC BY-SA 4.0


问:
Is there a way to simulate the C++ 'friend' concept in Java?
I would like to be able to write a Java class in one package which can access non-public methods of a class in another package without having to make it a subclass of the other class. Is this possible?</p>

答: eirikma's answer is easy and excellent.  I might add one more thing:  instead of having a publicly accessible method, getFriend() to get a friend which cannot be used, you could go one step further and disallow getting the friend without a token: getFriend(Service.FriendToken).  This FriendToken would be an inner public class with a private constructor, so that only Service could instantiate one.</p>

OwnerDisplayName: Matthew Murdoch

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Matthew Murdoch


问:
Python BeautifulSoup: Loop through elements to strip whitespace from within a function
I am trying to write a function that I can reuse to strip whitespace from scraped elements. I am scraping h2, li and p tags; they are currently being returned as <tag>    string    </tag> and I'd like to remove the whitespace and save the content back using *.get_text(strip=True).

h_content = soup.select('h2') will store all the h2 tags found.

p_content = soup.select('p') will store all the p tags found.

And so on.

I have been trying this but am not sure how to return the items to the original location, that is to say, return them here --> *_content

```<code>def remove_whitespace(tags):
    for item in tags:
        item.get_text(strip=True)
        return item
</code>```

The ideal situation is to end up with a function that I can reuse.

remove_whitespace(*_content)

答:
The error you got

AttributeError: 'unicode' object has no attribute 'get_text'

stems from an element (Tag) in given result set, that is not an instance or descendant of class NavigableString. As such it has no method get_text.

See also docs Miscellaneous common errors.

I would suggest to use the string-generators like stripped_strings or the simple text attribute:

```<code>def remove_whitespace(tags):
    texts = []
    for t in tags:
        print(t, type(t))  # debug print to see the type
        texts.append(t.text.strip())
    return texts
</code>```

See also:

'unicode' object has no attribute 'prettify'

How to make BeautifulSoup 'replace_with' attribute work with a 'unicode' object?

BeautifulSoup : TypeError: 'unicode' object is not callable

Body:
I am trying to write a function that I can reuse to strip whitespace from scraped elements. I am scraping h2, li and p tags; they are currently being returned as <tag>    string    </tag> and I'd like to remove the whitespace and save the content back using *.get_text(strip=True).

h_content = soup.select('h2') will store all the h2 tags found.

p_content = soup.select('p') will store all the p tags found.

And so on.

I have been trying this but am not sure how to return the items to the original location, that is to say, return them here --> *_content

def remove_whitespace(tags):
    for item in tags:
        item.get_text(strip=True)
        return item

The ideal situation is to end up with a function that I can reuse.

remove_whitespace(*_content)

Body:
The error you got

AttributeError: 'unicode' object has no attribute 'get_text'

stems from an element (Tag) in given result set, that is not an instance or descendant of class NavigableString. As such it has no method get_text.

See also docs Miscellaneous common errors.

I would suggest to use the string-generators like stripped_strings or the simple text attribute:

def remove_whitespace(tags):
    texts = []
    for t in tags:
        print(t, type(t))  # debug print to see the type
        texts.append(t.text.strip())
    return texts

See also:

'unicode' object has no attribute 'prettify'

How to make BeautifulSoup 'replace_with' attribute work with a 'unicode' object?

BeautifulSoup : TypeError: 'unicode' object is not callable


问:
xamarin - Why the first "refresh" in my tabbed page doesn't work, but the next ones are good?
I am a student working for a dev company, and i have to make an app to organize different book collections.
So, i had to make my "lists" into tabbed page, and cuz i don't know how many of them the user want to display, i have to add them dynamically, and control them with a specific tabbed page.
Everything work "fine", but, when i want to add a tab, the first time it doesn't work, then i try again, and it work fine (the previous one is taken into account this time), and the app start to work fine. Seem like it need time to "warm up", i don't know. I don't really understand why it only work after the 1st "refresh", so if someone had the same issue or have an idea, i will be grateful.
Thanks for reading me.

Code :
tabbedlist is the page that create the tab and the tabpage
addtabmenu is the page that add or remove which type i want to have on tab from a list

https://gfycat.com/tidywelldocumentedarcticduck

答:
i created a tab page. when the button in clicked it creates a new tab.

```<code><TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">
  <!--Pages can be added as references or inline-->
    <ContentPage Title="Tab 1" >
         <Button HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand" Clicked="Button_Clicked"/>
    </ContentPage>
    <ContentPage Title="Tab 2" />
  <ContentPage Title="Tab 3" />
</TabbedPage>
</code>```

code behind

```<code> private void Button_Clicked(object sender, EventArgs e)
        {
            NavigationPage navigationPage = new NavigationPage(new EmailDetails()); // EmailDetails is the page you want to add to the tab
            navigationPage.Title = "email";
            this.Children.Add(navigationPage);
        }
</code>```

Body:
i created a tab page. when the button in clicked it creates a new tab.

<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">
  <!--Pages can be added as references or inline-->
    <ContentPage Title="Tab 1" >
         <Button HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand" Clicked="Button_Clicked"/>
    </ContentPage>
    <ContentPage Title="Tab 2" />
  <ContentPage Title="Tab 3" />
</TabbedPage>

code behind

 private void Button_Clicked(object sender, EventArgs e)
        {
            NavigationPage navigationPage = new NavigationPage(new EmailDetails()); // EmailDetails is the page you want to add to the tab
            navigationPage.Title = "email";
            this.Children.Add(navigationPage);
        }


问:
Sticky header on top in canvas app - powerapps
I have header section in my app . In there i have many details like model name, model description, accuracy value , image and back button

after scrolled to a particular position in canvas app i want the header to show only the model name and back button (something like reducing the header  height to half of its original one)

Do we have anything in canvas app to behave similarly like this

In this example here

here is an header part

full header

when i scroll to some position only the below things will appear in UI as header

after scrolled

do we have anything similar to this in canvas app or any workaround to achieve this

答:
Depending on whether the important part of your header is at the top of your header or at its bottom:

At the top: make 2 containers. Only the sticky header elements should go into the first one, set this container to be on top. The rest of the header elements should go into the second, vertical container, on top, so they would disappear first when scrolling.

At the bottom: Add a vertical container with 2 child vertical containers. All header elements should go into the first one, with the sticky ones as last. Make a note of the sticky part's height, or group them. The second child container should host all scrollable elements. This one should have a height like (Screen height) - (sticky group's height) - (sticky footer's height, if any). This would result in the upper part of the header scroll out of sight but the sticky part always showing. Downside: double scrollbar.

Alternatively, you could set have a header container/group with conditional Y bound to a boolean variable. Any interaction with the non-header group could then trigger a negative shift of the header group leaving only the important part visible. You can also bind this to a manual collapse/x button.


Title: Sort date in list of strings in pandas column

Body:
I have data in this format

['96.22872386(2015-03-28)', 'None(2014-03-31)', '96.22872386(2015-03-30)', 'None(2017-03-31)']

['None(2015-10-01)', '1400(2021-11-23)', '1281(2019-07-26)', '690.854(2016-12-13)', '530(2021-08-21)']

Expected result:

['None(2014-03-31)', '96.22872386(2015-03-28)', '96.22872386(2015-03-30)', 'None(2017-03-31)']

['None(2015-10-01)', '690.854(2016-12-13)', '1281(2019-07-26)', '530(2021-08-21)', '1400(2021-11-23)']

Basically I want to sort the column values with respect to date.

Body:
If data are per rows use sorted with converting values to datetimes:

print (df)
                                                 col
0  ['96.22872386(2015-03-28)', 'None(2014-03-31)'...
1  ['None(2015-10-01)', '1400(2021-11-23)', '1281...

#if need convert values to lists
#import ast
#df['col'] = df['col'].apply(ast.literal_eval)

f = lambda x: sorted(x, key=lambda y: pd.to_datetime(y.split('(')[-1].strip(')')))
df['col'] = df['col'].apply(f)
print (df)
                                                 col
0  [None(2014-03-31), 96.22872386(2015-03-28), 96...
1  [None(2015-10-01), 690.854(2016-12-13), 1281(2...


问:
use css variable to generate class names in scss
is it possible to generate class names by css variables?

I am using scss in angular and I want to generate my class names base on

```<code>@input color
</code>```

property of component

so I store the input in a css variable named --color-variable to use it in my scss file.
I want to do something like this:

```<code>.ps-button--color-#{var(--color-variable)}{}
</code>```

this is the compiler error:

any suggestions would be helpfull.

答:
is it possible to generate class names by css variables?

Short answer:

No.

Longer answer:

CSS custom properties, also commonly called CSS variables, are known at runtime, while SASS variables are known at compile time. Since browsers can't understand SASS, it first needs to be compiled down to CSS and by that time, the SASS compiler won't know what the value of the CSS variable will be, so it throws a compile error.

Possible solution

Dynamically generate CSS based on your input and add it to the DOM.

Body:
is it possible to generate class names by css variables?

I am using scss in angular and I want to generate my class names base on

@input color

property of component

so I store the input in a css variable named --color-variable to use it in my scss file.
I want to do something like this:

.ps-button--color-#{var(--color-variable)}{}

this is the compiler error:

any suggestions would be helpfull.


问:
Fixing header (navbar) in webview flutter
I am currently working on a project where I need to convert a website to a mobile app using flutter
I did it with the widget WEBVIEW but the header of the webview in my mobile is not fixed when i scroll the page the header (navBar) of my website scroll too but i want it to be fixed even if i scroll the page
this is my code :

```<code>import 'dart:async';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with TickerProviderStateMixin{

  final Completer<WebViewController> _controller =
  Completer<WebViewController>();

  late WebViewController _webViewController;

  @override
  Widget build(BuildContext context) {
    String hexString = "1b5c80";
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Welcome to Flutter',
      home: Scaffold(
        body: WebView(
          initialUrl: "https://www.journaldunet.fr/web-tech/dictionnaire-du-webmastering/1203251-blog-definition-et-acteurs/",
          javascriptMode: JavascriptMode.unrestricted,
          onWebViewCreated: (WebViewController webViewController) {
            _webViewController = webViewController;
            _controller.complete(webViewController);
            },
          onPageFinished: (String url) {
            _webViewController.evaluateJavascript("javascript:(function() { " +
                "var footer = document.getElementsByTagName('footer')[0];" +
                "footer.parentNode.removeChild(footer);" +
                "})()");
            },
          gestureNavigationEnabled: true,
        ),
      ),
    );
  }

  JavascriptChannel _toasterJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'Toaster',
        onMessageReceived: (JavascriptMessage message) {
          // ignore: deprecated_member_use
          Scaffold.of(context).showSnackBar(
            SnackBar(content: Text(message.message)),
          );
        });
  }
}
</code>```

this is my mobiel app :

答:
If you build build own AppBar in Flutter then it will be Fix according to you.
But If header came from Webview then you can not control this...
Because Webview is only view of your website inside your flutter app...</p>

Body:
I am currently working on a project where I need to convert a website to a mobile app using flutter
I did it with the widget WEBVIEW but the header of the webview in my mobile is not fixed when i scroll the page the header (navBar) of my website scroll too but i want it to be fixed even if i scroll the page
this is my code :

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with TickerProviderStateMixin{

  final Completer<WebViewController> _controller =
  Completer<WebViewController>();

  late WebViewController _webViewController;

  @override
  Widget build(BuildContext context) {
    String hexString = "1b5c80";
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Welcome to Flutter',
      home: Scaffold(
        body: WebView(
          initialUrl: "https://www.journaldunet.fr/web-tech/dictionnaire-du-webmastering/1203251-blog-definition-et-acteurs/",
          javascriptMode: JavascriptMode.unrestricted,
          onWebViewCreated: (WebViewController webViewController) {
            _webViewController = webViewController;
            _controller.complete(webViewController);
            },
          onPageFinished: (String url) {
            _webViewController.evaluateJavascript("javascript:(function() { " +
                "var footer = document.getElementsByTagName('footer')[0];" +
                "footer.parentNode.removeChild(footer);" +
                "})()");
            },
          gestureNavigationEnabled: true,
        ),
      ),
    );
  }

  JavascriptChannel _toasterJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'Toaster',
        onMessageReceived: (JavascriptMessage message) {
          // ignore: deprecated_member_use
          Scaffold.of(context).showSnackBar(
            SnackBar(content: Text(message.message)),
          );
        });
  }
}

this is my mobiel app :


问:
when opening DropdownMenu, how can I cancel keyboard auto-close behavior
when I open DropdownMenu, my keyboard auto-close. This behavior is not my expect.
I expect my keyboard to remain open when I open the DropdownMenu.

current behavior:

want behavior:

答:
Thanks to my friends in the compose community for helping me with this on slack.

Just set the properties.focusable property to false

var content by remember { mutableStateOf("") }
var deadLineMenuExpanded by remember { mutableStateOf(false) }
Column(modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally) {
    TextField(value = content, onValueChange = {content = it})
    Box() {
        TextButton(onClick = { deadLineMenuExpanded = true }) {
            Text("open Menu")
        }
        DropdownMenu(
            expanded = deadLineMenuExpanded,
            onDismissRequest = { deadLineMenuExpanded = false },
            properties = PopupProperties(focusable = false)
        ) {
            DropdownMenuItem(onClick = {
                deadLineMenuExpanded = false
            }) {
                androidx.compose.material.Text("today")
            }
        }

    }
}
```


问:
How to 'narrow' onchange for specific id?
I found this cod on jquery web

```<code>$("select").change(function () {
      var str = "";
      $("select option:selected").each(function () {
            str += $(this).text() + " ";
          });
      $("div").text(str);
    })
    .change();
</code>```

I can use it for I want but I want this function to be fired only for #my_id. I tried to insert #my_id after both selects but then the function does nothing.

I though I could bind this function to only select with specific id.

答:
Maybe this:</p>

```<code>$("select#my_id").change(function() {
    var selOpts = jQuery.map($(":selected", $(this)), function(opt, index) {
        return $(opt).text();
    });
    $("div").text(selOpts.join(" "));
}).change();
</code>```

Body:
I found this cod on jquery web

$("select").change(function () {
      var str = "";
      $("select option:selected").each(function () {
            str += $(this).text() + " ";
          });
      $("div").text(str);
    })
    .change();

I can use it for I want but I want this function to be fired only for #my_id. I tried to insert #my_id after both selects but then the function does nothing.

I though I could bind this function to only select with specific id.

Body:
Maybe this:

$("select#my_id").change(function() {
    var selOpts = jQuery.map($(":selected", $(this)), function(opt, index) {
        return $(opt).text();
    });
    $("div").text(selOpts.join(" "));
}).change();


问:
How do I make Jenkins 2.0 execute a sh command in the same directory as the checkout?
Here's my Jenkins 2.x pipeline:

```<code>node ('master'){
    stage 'Checkout'
    checkout scm
    stage "Build Pex"
    sh('build.sh')
}
</code>```

When I run this pipeline the checkout puts the code into to the workspace as expected, however instead of expecting to find the script in workspace/ (it's really there!), it looks in an unrelated directory: workspace@tmp/durable-d812f509.

```<code>Entering stage Build Pex
Proceeding
[Pipeline] sh
[workspace] Running shell script
+ build.sh
/home/conmonsysdev/deployments/jenkins_ci_2016_interns/jenkins_home/jobs/pex/branches/master/workspace@tmp/durable-d812f509/script.sh: line 2: build.sh: command not found
</code>```

How do I modify this Jenkinsfile so that build.sh is executed in the exact same directory as where I checked out the project source code?

答:
Use the GIT_CHECKOUT_DIR environment variable

Jenkinsfile:

```<code>pipeline {
  agent any
  stages {
    stage('Install dependencies') {
      steps {
        dir(GIT_CHECKOUT_DIR) {
          // now everything is executed in your checkout directory
          sh 'yarn'
        }
      }
    }
  }
  post {
    // ...
  }
}
</code>```

Set your GIT_CHECKOUT_DIR while setting up your pipeline. See this question:

List of more environment variables:

${YOUR_JENKINS_HOST}/env-vars.html

example: http://localhost:8000/env-vars.html

The most upvoted answer is dangerous and brittle. No need to use static operating system dependant ABSOLUTE PATHs in multiple places that break your builds once you change the machine.

Body:
Here's my Jenkins 2.x pipeline:

node ('master'){
    stage 'Checkout'
    checkout scm
    stage "Build Pex"
    sh('build.sh')
}

When I run this pipeline the checkout puts the code into to the workspace as expected, however instead of expecting to find the script in workspace/ (it's really there!), it looks in an unrelated directory: workspace@tmp/durable-d812f509.

Entering stage Build Pex
Proceeding
[Pipeline] sh
[workspace] Running shell script
+ build.sh
/home/conmonsysdev/deployments/jenkins_ci_2016_interns/jenkins_home/jobs/pex/branches/master/workspace@tmp/durable-d812f509/script.sh: line 2: build.sh: command not found

How do I modify this Jenkinsfile so that build.sh is executed in the exact same directory as where I checked out the project source code?

Body:
Use the GIT_CHECKOUT_DIR environment variable

Jenkinsfile:

pipeline {
  agent any
  stages {
    stage('Install dependencies') {
      steps {
        dir(GIT_CHECKOUT_DIR) {
          // now everything is executed in your checkout directory
          sh 'yarn'
        }
      }
    }
  }
  post {
    // ...
  }
}

Set your GIT_CHECKOUT_DIR while setting up your pipeline. See this question:

List of more environment variables:

${YOUR_JENKINS_HOST}/env-vars.html

example: http://localhost:8000/env-vars.html

The most upvoted answer is dangerous and brittle. No need to use static operating system dependant ABSOLUTE PATHs in multiple places that break your builds once you change the machine.


问:
How to center an iframe horizontally?
Consider the following example: (live demo)

HTML:

```<code><div>div</div>
<iframe></iframe>
</code>```

CSS:

```<code>div, iframe {
    width: 100px;
    height: 50px;
    margin: 0 auto;
    background-color: #777;
}
</code>```

Result:

Why the iframe is not centrally aligned like the div? How could I centrally align it?

Title: How to center an iframe horizontally?

Body:
Consider the following example: (live demo)

HTML:

div

CSS:

div, iframe {
    width: 100px;
    height: 50px;
    margin: 0 auto;
    background-color: #777;
}

Result:

Why the iframe is not centrally aligned like the div? How could I centrally align it?

Body:
<iframe src="https://www.facebook.com/plugins/page.php?href=https%3A%2F%2Fwww.facebook.com%2FRishabh-Cars-Jodhpur-110479104559774&tabs=timeline&width=500&height=1200&small_header=false&adapt_container_width=true&hide_cover=false&show_facepile=true&appId" width="500" height="1200" style="border:none;overflow:hidden;display:block;margin:0 auto;" scrolling="yes" frameborder=".6" allowfullscreen="true" allow="autoplay; clipboard-write; encrypted-media; picture-in-picture; web-share"></iframe>

use it and embed facebook in iframe in center of html page


问:
popAndPushNamed - Unhandled Exception: This widget has been unmounted, so the State no longer has a context (and should be considered defunct)
I briefly explain my problem, when I create and name "something" in my application, I let 760 milliseconds pass to go to another page. However the problem is that in that lapse of time, if I exit with the back button of my AppBar, I get the following error (the function that inidicates onTitleSelectionAtCreate is the one that I use the popAndPushNamed)

```<code>[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: This widget has been unmounted, so the State no longer has a context (and should be considered defunct).
E/flutter (28951): Consider canceling any active work during "dispose" or using the "mounted" getter to determine if the State is still active.
</code>```

Here is my code :

```<code>class InitialRemarkInfo extends StatefulWidget {
  final bool? isCreated;

  const InitialRemarkInfo({
    Key? key,
    required this.isCreated,
  }) : super(key: key);

  @override
  _InitialRemarkInfoState createState() => _InitialRemarkInfoState();
}

class _InitialRemarkInfoState extends State<InitialRemarkInfo>
    with TickerProviderStateMixin {

  double _height = 0;
  double _width = 0;
  bool _resized = false;

  @override
  void initState() {
    super.initState();

    if (!this.widget.isCreated!)
      BlocProvider.of<SomethingBloc>(context).add(InitializeEvent());
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: this._onPopBack,
      child: Scaffold(
        // * APP BAR
        appBar: AppBar(
          title: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Text(this.localizedString('newSomething')!),
            ],
          ),
          leading: IconButton(
            splashRadius: 1,
            icon: Icon(Icons.arrow_back),
            onPressed: _onPopBack,
          ),
          backgroundColor: DesignConstants.darkBlueBackground,
        ),

        body: BlocConsumer<SomethingBloc, SomethingState>(
          // * LISTENER
          listener: (context, state) async {

            [...]

          },
          builder: (context, state) {
            // * LOADED
            if (state is SomethingLoaded)
              return Stack(
                children: [
                  SingleChildScrollView(
                    physics: AlwaysScrollableScrollPhysics(),
                    child: Column(
                      children: [
                        // * GROWING SPACE (to simulate animation)
                        new AnimatedSize(
                          curve: Curves.easeIn,
                          child: new Container(
                            width: _width,
                            height: _height,
                            color: Colors.transparent,
                          ),
                          duration: new Duration(milliseconds: 700),
                        ),

                        [...]

                        // * TITLE
                        DataRo(
                          title: 'title',
                          icon: Icons.arrow_drop_down,
                          isCreation: true,
                          onTitleSelectionAtCreate: () =>
                              _onTitleSelectionAtCreate(), // Function
                        ),
                      ],
                    ),
                  ),
                ],
              );

            // * DEFAULT
            return Container();
          },
        ),
      ),
    );
  }

  //============================================================================
  // ON POP BACK
  //
  Future<bool> _onPopBack() async {
    BlocProvider.of<SomethingBloc>(context).add(
        ReloadList(isCreation: true, isSaving: false));

    return false;
  }

  // ==========================================================================
  // ON TITLE SELECTION AT CREATE
  //
  void _onTitleSelectionAtCreate() {
      setState(() {
        if (_resized) {
          this._resized = false;
          this._height = 0;
          this._width = 0;
        } else {
          this._resized = true;
          this._height = Device.screenHeight / 3;
          this._width = Device.screenWidth;
        }
      }); // To animate something not relevant

    Future.delayed(const Duration(milliseconds: 730), () {
      Navigator.of(context).popAndPushNamed(
        PageNames.something,
        arguments: {
          "info": null,
        },
      );
    });
  }
}
</code>```

答:
Use mounted getter to determine if the State is still active

```<code>    Future.delayed(const Duration(milliseconds: 730), () {
     if(mounted)
      Navigator.of(context).popAndPushNamed(
        PageNames.something,
        arguments: {
          "info": null,
        },
      );
    });
</code>```

Body:
I briefly explain my problem, when I create and name "something" in my application, I let 760 milliseconds pass to go to another page. However the problem is that in that lapse of time, if I exit with the back button of my AppBar, I get the following error (the function that inidicates onTitleSelectionAtCreate is the one that I use the popAndPushNamed)

[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: This widget has been unmounted, so the State no longer has a context (and should be considered defunct).
E/flutter (28951): Consider canceling any active work during "dispose" or using the "mounted" getter to determine if the State is still active.

Here is my code :

class InitialRemarkInfo extends StatefulWidget {
  final bool? isCreated;

  const InitialRemarkInfo({
    Key? key,
    required this.isCreated,
  }) : super(key: key);

  @override
  _InitialRemarkInfoState createState() => _InitialRemarkInfoState();
}

class _InitialRemarkInfoState extends State<InitialRemarkInfo>
    with TickerProviderStateMixin {

  double _height = 0;
  double _width = 0;
  bool _resized = false;

  @override
  void initState() {
    super.initState();

    if (!this.widget.isCreated!)
      BlocProvider.of<SomethingBloc>(context).add(InitializeEvent());
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: this._onPopBack,
      child: Scaffold(
        // * APP BAR
        appBar: AppBar(
          title: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Text(this.localizedString('newSomething')!),
            ],
          ),
          leading: IconButton(
            splashRadius: 1,
            icon: Icon(Icons.arrow_back),
            onPressed: _onPopBack,
          ),
          backgroundColor: DesignConstants.darkBlueBackground,
        ),

        body: BlocConsumer<SomethingBloc, SomethingState>(
          // * LISTENER
          listener: (context, state) async {

            [...]

          },
          builder: (context, state) {
            // * LOADED
            if (state is SomethingLoaded)
              return Stack(
                children: [
                  SingleChildScrollView(
                    physics: AlwaysScrollableScrollPhysics(),
                    child: Column(
                      children: [
                        // * GROWING SPACE (to simulate animation)
                        new AnimatedSize(
                          curve: Curves.easeIn,
                          child: new Container(
                            width: _width,
                            height: _height,
                            color: Colors.transparent,
                          ),
                          duration: new Duration(milliseconds: 700),
                        ),

                        [...]

                        // * TITLE
                        DataRo(
                          title: 'title',
                          icon: Icons.arrow_drop_down,
                          isCreation: true,
                          onTitleSelectionAtCreate: () =>
                              _onTitleSelectionAtCreate(), // Function
                        ),
                      ],
                    ),
                  ),
                ],
              );

            // * DEFAULT
            return Container();
          },
        ),
      ),
    );
  }

  //============================================================================
  // ON POP BACK
  //
  Future<bool> _onPopBack() async {
    BlocProvider.of<SomethingBloc>(context).add(
        ReloadList(isCreation: true, isSaving: false));

    return false;
  }

  // ==========================================================================
  // ON TITLE SELECTION AT CREATE
  //
  void _onTitleSelectionAtCreate() {
      setState(() {
        if (_resized) {
          this._resized = false;
          this._height = 0;
          this._width = 0;
        } else {
          this._resized = true;
          this._height = Device.screenHeight / 3;
          this._width = Device.screenWidth;
        }
      }); // To animate something not relevant

    Future.delayed(const Duration(milliseconds: 730), () {
      Navigator.of(context).popAndPushNamed(
        PageNames.something,
        arguments: {
          "info": null,
        },
      );
    });
  }
}

Body:
Use mounted getter to determine if the State is still active

    Future.delayed(const Duration(milliseconds: 730), () {
     if(mounted)
      Navigator.of(context).popAndPushNamed(
        PageNames.something,
        arguments: {
          "info": null,
        },
      );
    });


问:
After i reload i want to keep the local storage values
This is my function:

function render() {
  let list = document.getElementById('myNotes');
  trashFolderModal = document.getElementById('allBlur');
  list.innerHTML = localStorage.setItem(key, text);

  for (let i = 0; i < titles.length; i++) {
    const title = titles[i];
    const note = notes[i];
    list.innerHTML += card(title, note, i);
  }
}
```

And here is my Note Website (you can see the source code):
http://patrick-sterz.developerakademie.com/Notizblock2/index%282%29.html

答:
setItem returns undefined.

I suspect you need to revisit what you want to do.

Normally we do this when the list changes

```<code> localStorage.setItem("list",JSON.stringify(myListArray));
</code>```

and when we load the page we do a

```<code>let listContent = localStorage.getItem("list");
let myListArray =  listContent ? JSON.parse(listContent) : [];
</code>```

Body:
This is my function:

function render() {
  let list = document.getElementById('myNotes');
  trashFolderModal = document.getElementById('allBlur');
  list.innerHTML = localStorage.setItem(key, text);

  for (let i = 0; i < titles.length; i++) {
    const title = titles[i];
    const note = notes[i];
    list.innerHTML += card(title, note, i);
  }
}

And here is my Note Website (you can see the source code):
http://patrick-sterz.developerakademie.com/Notizblock2/index%282%29.html

Body:
setItem returns undefined.

I suspect you need to revisit what you want to do.

Normally we do this when the list changes

 localStorage.setItem("list",JSON.stringify(myListArray));

and when we load the page we do a

let listContent = localStorage.getItem("list");
let myListArray =  listContent ? JSON.parse(listContent) : [];


问:
jQuery Ajax call - Set variable value on success
I have an application that I am writing that modifies data on a cached object in the server.  The modifications are performed through an ajax call that basically updates properties of that object.  When the user is done working, I have a basic 'Save Changes' button that allows them to Save the data and flush the cached object.

In order to protect the user, I want to warn them if the try to navigate away from the page when modifications have been made to the server object if they have not saved.  So, I created a web service method called IsInitialized that will return true or false based on whether or not changes have been saved.  If they have not been saved, I want to prompt the user and give them a chance to cancel their navigation request.

Here's my problem - although I have the calls working correctly, I can't seem to get the ajax success call to set the variable value on its callback function.  Here's the code I have now.

```<code>   ////Catches the users to keep them from navigation off the page w/o saved changes...
window.onbeforeunload = CheckSaveStatus;
var IsInitialized;

function CheckSaveStatus() {

    var temp = $.ajax({
        type: "POST",
        url: "URL.asmx/CheckIfInstanceIsInitilized",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(result) {
            IsInitialized = result.d;
        },
        error: function(xmlHttpRequest, status, err) {
            alert(xmlHttpRequest.statusText + " " + xmlHttpRequest.status + " : " + xmlHttpRequest.responseText);
        }

    });

    if (IsInitialized) {
        return "You currently have unprocessed changes for this Simulation.";
    }
}
</code>```

I feel that I might be trying to use the Success callback in an inappropriate manner.  How do I set a javascript variable on the Success callback so that I can decide whether or not the user should be prompted w/ the unsaved changes message?

As was just pointed out, I am making an asynchronous call, which means the rest of the code gets called before my method returns.  Is there a way to use that ajax call, but still catch the window.onunload event? (without making synchronos ajax)

答:
Looks like the best approach for me was to use the async: false option on my ajax call.  Although I understand Rashack's hesitation for doing this, I think that this situation justifies the means.

Also great point by Jerph about making sure that I don't leave the user hanging while I am trying to verify their status.  That coupled w/ the timeout option is important.

Thanks to everyone who commented.

OwnerDisplayName: Nathan

Body:
I have an application that I am writing that modifies data on a cached object in the server.  The modifications are performed through an ajax call that basically updates properties of that object.  When the user is done working, I have a basic 'Save Changes' button that allows them to Save the data and flush the cached object.

In order to protect the user, I want to warn them if the try to navigate away from the page when modifications have been made to the server object if they have not saved.  So, I created a web service method called IsInitialized that will return true or false based on whether or not changes have been saved.  If they have not been saved, I want to prompt the user and give them a chance to cancel their navigation request.

Here's my problem - although I have the calls working correctly, I can't seem to get the ajax success call to set the variable value on its callback function.  Here's the code I have now.

   ////Catches the users to keep them from navigation off the page w/o saved changes...
window.onbeforeunload = CheckSaveStatus;
var IsInitialized;

function CheckSaveStatus() {

    var temp = $.ajax({
        type: "POST",
        url: "URL.asmx/CheckIfInstanceIsInitilized",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(result) {
            IsInitialized = result.d;
        },
        error: function(xmlHttpRequest, status, err) {
            alert(xmlHttpRequest.statusText + " " + xmlHttpRequest.status + " : " + xmlHttpRequest.responseText);
        }

    });

    if (IsInitialized) {
        return "You currently have unprocessed changes for this Simulation.";
    }
}

I feel that I might be trying to use the Success callback in an inappropriate manner.  How do I set a javascript variable on the Success callback so that I can decide whether or not the user should be prompted w/ the unsaved changes message?

As was just pointed out, I am making an asynchronous call, which means the rest of the code gets called before my method returns.  Is there a way to use that ajax call, but still catch the window.onunload event? (without making synchronos ajax)

LastEditorDisplayName: Nathan


问:
warning message "argument is not an atomic vector; coercing" when mutating in a list column
I do some reshaping within my data. I'm basically doing two things:

All x cases with the same value should be nested/summarized into a list column.

For the remaining x values I will have a character value in y separated by one or more commas. I want to split up these character values into separate values and then put that into the existing y list column as character vector. So e.g. for x == "second", I do have the char vector "C, D" (so just one value) and I want to create a char vector c("C", "D"), i.e. with length 2.

The code below seems to do what I want, but I'm getting a warning message. Although it is only a warning message, I want to make sure I'm doing the right thing.

```<code>library(tidyverse)
df <- data.frame(x = c("first", "first", "second", "third"),
                 y = c("A", "B", "C, D", "E, F, G"))

df

       x       y
1  first       A
2  first       B
3 second    C, D
4  third E, F, G
</code>```

.

```<code>df |>
  group_by(x) |>
  summarise(y = list(y)) |>
  rowwise() |>
  mutate(y = list(as.vector(y, mode = "character"))) |>
  ungroup() |>
  mutate(across(y, ~if_else(!str_detect(x, "first"), str_split(., ", "), y)))
</code>```

which (correctly) gives:

```<code># A tibble: 3 x 2
  x      y
  <chr>  <list>
1 first  <chr [2]>
2 second <chr [2]>
3 third  <chr [2]>
</code>```

But with a warning:

```<code>Warning message:
Problem with `mutate()` input `..1`.
i `..1 = across(...)`.
i argument is not an atomic vector; coercing
</code>```

Waht can/should I do?

答:
You can get this result more easily with tidyr::separate_rows:

df |>
  separate_rows(y) |>
  group_by(x) |>
  summarise(y = list(y))

#     x      y
#     <chr>  <list>
#   1 first  <chr [2]>
#   2 second <chr [2]>
#   3 third  <chr [3]>
```

Body:
I do some reshaping within my data. I'm basically doing two things:

All x cases with the same value should be nested/summarized into a list column.

For the remaining x values I will have a character value in y separated by one or more commas. I want to split up these character values into separate values and then put that into the existing y list column as character vector. So e.g. for x == "second", I do have the char vector "C, D" (so just one value) and I want to create a char vector c("C", "D"), i.e. with length 2.

The code below seems to do what I want, but I'm getting a warning message. Although it is only a warning message, I want to make sure I'm doing the right thing.

library(tidyverse)
df <- data.frame(x = c("first", "first", "second", "third"),
                 y = c("A", "B", "C, D", "E, F, G"))

df

       x       y
1  first       A
2  first       B
3 second    C, D
4  third E, F, G

.

df |>
  group_by(x) |>
  summarise(y = list(y)) |>
  rowwise() |>
  mutate(y = list(as.vector(y, mode = "character"))) |>
  ungroup() |>
  mutate(across(y, ~if_else(!str_detect(x, "first"), str_split(., ", "), y)))

which (correctly) gives:

# A tibble: 3 x 2
  x      y
  <chr>  <list>
1 first  <chr [2]>
2 second <chr [2]>
3 third  <chr [2]>

But with a warning:

Warning message:
Problem with `mutate()` input `..1`.
i `..1 = across(...)`.
i argument is not an atomic vector; coercing

Waht can/should I do?


问:
AWS Glue python job limits the data amount to write in S3 bucket?
I've created a Glue job to read data from glue catalog and save it to an s3 bucket in parquet format. It works correctly, but the number of items is limited to 20. So every time the job is triggered, only 20 items gets saved in the bucket, and I would like to save all of them. Maybe I'm missing some additional property in the python script.

Here is the script (generated by AWS):

```<code>import sys
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.job import Job

args = getResolvedOptions(sys.argv, ['JOB_NAME'])

sc = SparkContext()
glueContext = GlueContext(sc)
spark = glueContext.spark_session
job = Job(glueContext)
job.init(args['JOB_NAME'], args)
transformation_ctx = "datasource0"]

datasource0 = glueContext.create_dynamic_frame.from_catalog(database = "cargoprobe_data", table_name = "dev_scv_completed_executions", transformation_ctx = "datasource0")

applymapping1 = ApplyMapping.apply(frame = datasource0, mappings = [*field list*], transformation_ctx = "applymapping1")

resolvechoice2 = ResolveChoice.apply(frame = applymapping1, choice = "make_struct", transformation_ctx = "resolvechoice2")

dropnullfields3 = DropNullFields.apply(frame = resolvechoice2, transformation_ctx = "dropnullfields3")

datasink4 = glueContext.write_dynamic_frame.from_options(frame = dropnullfields3, connection_type = "s3", connection_options = {"path": "s3://bucketname"}, format = "parquet", transformation_ctx = "datasink4")

job.commit()
</code>```

答:
This is done automatically in the background, it is called partitioning. You can repartition by calling

```<code>partitioned_df = dropnullfields3.repartition(1)
</code>```

to repartition your DynamicFrame to one file.

Body:
I've created a Glue job to read data from glue catalog and save it to an s3 bucket in parquet format. It works correctly, but the number of items is limited to 20. So every time the job is triggered, only 20 items gets saved in the bucket, and I would like to save all of them. Maybe I'm missing some additional property in the python script.

Here is the script (generated by AWS):

import sys
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.job import Job

args = getResolvedOptions(sys.argv, ['JOB_NAME'])

sc = SparkContext()
glueContext = GlueContext(sc)
spark = glueContext.spark_session
job = Job(glueContext)
job.init(args['JOB_NAME'], args)
transformation_ctx = "datasource0"]

datasource0 = glueContext.create_dynamic_frame.from_catalog(database = "cargoprobe_data", table_name = "dev_scv_completed_executions", transformation_ctx = "datasource0")

applymapping1 = ApplyMapping.apply(frame = datasource0, mappings = [*field list*], transformation_ctx = "applymapping1")

resolvechoice2 = ResolveChoice.apply(frame = applymapping1, choice = "make_struct", transformation_ctx = "resolvechoice2")

dropnullfields3 = DropNullFields.apply(frame = resolvechoice2, transformation_ctx = "dropnullfields3")

datasink4 = glueContext.write_dynamic_frame.from_options(frame = dropnullfields3, connection_type = "s3", connection_options = {"path": "s3://bucketname"}, format = "parquet", transformation_ctx = "datasink4")

job.commit()

Body:
This is done automatically in the background, it is called partitioning. You can repartition by calling

partitioned_df = dropnullfields3.repartition(1)

to repartition your DynamicFrame to one file.


问:
Trying to set up a heroku staging site - "Resource not found "
I'm working on an existing rails project which is deployed on heroku.  I'm trying to set up a staging server which deploys from the staging branch.  (currently master deploys to production).

I'm following this page
http://devcenter.heroku.com/articles/multiple-environments#starting_with_a_production_app

and i'm on the section "Starting from a production app".  The code it gives is

heroku create --stack [production stack] --remote staging --addons newrelic:bronze,logging:expanded

I'm trying to adapt this to my own needs but i get a message back Resource not found.

Here's what i get for "heroku apps"

```<code>custom_domains:basic
exceptional:basic
logging:expanded
shared-database:5mb
</code>```

If i do heroku list i get this

```<code>buddystef                 <project manager's email>
vivid-window-286
vivid-earth-537
</code>```

where 'buddystef' is the production version of the app.  So, i'm trying this:

heroku create --stack [buddystef stack] --remote buddy-staging --addons custom_domains:basic,exceptional:basic,logging:expanded,shared-database:5mb

And i'm getting Resource not found

Do i need to set up a seperate git repo first for the staging branch?  If so, what's the best way to do this?

Grateful for any advice - max

EDIT - the "Resource not found" message seems (after googling) to be associated with logging in with the wrong credentials.  But, i'm logging in as the owner of the buddystef project.

答: I use Heroku San, which does some of the legwork for you. Github | Tutorial</p>

Body:
I'm working on an existing rails project which is deployed on heroku.  I'm trying to set up a staging server which deploys from the staging branch.  (currently master deploys to production).

I'm following this page
http://devcenter.heroku.com/articles/multiple-environments#starting_with_a_production_app

and i'm on the section "Starting from a production app".  The code it gives is

heroku create --stack [production stack] --remote staging --addons newrelic:bronze,logging:expanded

I'm trying to adapt this to my own needs but i get a message back Resource not found.

Here's what i get for "heroku apps"

custom_domains:basic
exceptional:basic
logging:expanded
shared-database:5mb

If i do heroku list i get this

buddystef                 <project manager's email>
vivid-window-286
vivid-earth-537

where 'buddystef' is the production version of the app.  So, i'm trying this:

heroku create --stack [buddystef stack] --remote buddy-staging --addons custom_domains:basic,exceptional:basic,logging:expanded,shared-database:5mb

And i'm getting Resource not found

Do i need to set up a seperate git repo first for the staging branch?  If so, what's the best way to do this?

Grateful for any advice - max

EDIT - the "Resource not found" message seems (after googling) to be associated with logging in with the wrong credentials.  But, i'm logging in as the owner of the buddystef project.


问:
Can't understand the use of window.onscroll = null in React
What's the use of window.onscroll = null here?
It shows no difference even when i comment that last line out.</p>
```<code>const [isScrolled, setIsScrolled] = useState(false);

window.onscroll = () => {
    setIsScrolled(window.pageYOffset === 0? false : true)
    console.log(isScrolled);

    return () => (window.onscroll = null);
};
</code>```

答:
As written, the window.onscroll = null is useless. It will never be executed. However, this code is suspiciously close to code that is useful. The following code is what i would expect to see:

```<code>const [isScrolled, setIsScrolled] = useState(false);
useEffect(() => {
  window.onscroll = () => {
    setIsScrolled(window.pageYOffset === 0? false : true)
  };
  return () => (window.onscroll = null);
}, []);
</code>```

In this modified version, return () => (window.onscroll = null) is returning a cleanup function for the effect. When the component unmounts, this function runs and removes the event listener. This is important to do so that you avoid memory leaks.

Body:
What's the use of window.onscroll = null here?
It shows no difference even when i comment that last line out.

const [isScrolled, setIsScrolled] = useState(false);

window.onscroll = () => {
    setIsScrolled(window.pageYOffset === 0? false : true)
    console.log(isScrolled);

    return () => (window.onscroll = null);
};

Body:
As written, the window.onscroll = null is useless. It will never be executed. However, this code is suspiciously close to code that is useful. The following code is what i would expect to see:

const [isScrolled, setIsScrolled] = useState(false);
useEffect(() => {
  window.onscroll = () => {
    setIsScrolled(window.pageYOffset === 0? false : true)
  };
  return () => (window.onscroll = null);
}, []);

In this modified version, return () => (window.onscroll = null) is returning a cleanup function for the effect. When the component unmounts, this function runs and removes the event listener. This is important to do so that you avoid memory leaks.


问:
Regex replace word in string that are not in quotes
I'm looking to do replacements in unknown third-party inputs in strings that sometimes have quotes among them.

I want to replace a wholeword whereever it occurs unless it's in double or single-quotes, and unless the quote is escaped.

Example: Replacing FOO by BAR

Input:

```<code>FOO "FOO" 'FOO' "    1 + FOO + 2 " ABCFOOXYZ "  str1\"FOO\"str3'FOO'\'\'" '  str1\'FOOstr3"FOO"\"\"' \"FOO\"
</code>```

Expected output:

```<code>BAR "FOO" 'FOO' "    1 + FOO + 2 " ABCFOOXYZ "  str1\"FOO\"str3'FOO'\'\'" '  str1\'FOOstr3"FOO"\"\"' \"BAR\"
</code>```

More tests:

```<code>name: FOO
favoriteQuote: "I am my own FOO."
children: 'FOO\'s children'
cars: ownersList[FOO]
statement = FOO + " is the owner of the house."
</code>```

Expected output:

```<code>name: BAR
favoriteQuote: "I am my own FOO."
children: 'FOO\'s children'
cars: ownersList[BAR]
statement = BAR + " is the owner of the house."
</code>```

I saw this question: Match and replace a word not in quotes (string contains escaped quotes) which I thought was similar and could be a good starting point the accepted answer does not work at all:

https://regex101.com/r/Lfan64/5

If anyone could help me get the expected result from my regex that would be great, thanks.

答:
You can use

const text = String.raw`name: FOO
favoriteQuote: "I am my own FOO."
children: 'FOO\'s children'
cars: ownersList[FOO]
statement = FOO + " is the owner of the house."
FOO "FOO" 'FOO' "    1 + FOO + 2 " ABCFOOXYZ "  str1\"FOO\"str3'FOO'\'\'" '  str1\'FOOstr3"FOO"\"\"' \"FOO\"`
console.log( text.replace(
  /((?:[^\\]|^)(?:\\{2})*(?:"[^"\\]*(?:\\[^][^"\\]*)*"|'[^'\\]*(?:\\[^][^'\\]*)*'))|FOO/g,
  (match, group) => group || "BAR"
))```

Details:

((?:[^\\]|^)(?:\\{2})*(?:"[^"\\]*(?:\\[^][^"\\]*)*"|'[^'\\]*(?:\\[^][^'\\]*)*')) - Group 1:

(?:[^\\]|^) - a char other than \ or start of string

(?:\\{2})* - zero or more sequences of double backslash

(?:"[^"\\]*(?:\\[^][^"\\]*)*"|'[^'\\]*(?:\\[^][^'\\]*)*') - either of a double or single quoted string literal pattern with escape sequence support

| - or

FOO - a FOO string in any other context.

The (match, group) => group || "BAR" replacement means that if Group 1 matches, the replacement is Group 1 value, else, the replacement is BAR.

Body:
I'm looking to do replacements in unknown third-party inputs in strings that sometimes have quotes among them.

I want to replace a wholeword whereever it occurs unless it's in double or single-quotes, and unless the quote is escaped.

Example: Replacing FOO by BAR

Input:

FOO "FOO" 'FOO' "    1 + FOO + 2 " ABCFOOXYZ "  str1\"FOO\"str3'FOO'\'\'" '  str1\'FOOstr3"FOO"\"\"' \"FOO\"

Expected output:

BAR "FOO" 'FOO' "    1 + FOO + 2 " ABCFOOXYZ "  str1\"FOO\"str3'FOO'\'\'" '  str1\'FOOstr3"FOO"\"\"' \"BAR\"

More tests:

name: FOO
favoriteQuote: "I am my own FOO."
children: 'FOO\'s children'
cars: ownersList[FOO]
statement = FOO + " is the owner of the house."

Expected output:

name: BAR
favoriteQuote: "I am my own FOO."
children: 'FOO\'s children'
cars: ownersList[BAR]
statement = BAR + " is the owner of the house."

I saw this question: Match and replace a word not in quotes (string contains escaped quotes) which I thought was similar and could be a good starting point the accepted answer does not work at all:

https://regex101.com/r/Lfan64/5

If anyone could help me get the expected result from my regex that would be great, thanks.

Body:
You can use

const text = String.raw`name: FOO
favoriteQuote: "I am my own FOO."
children: 'FOO\'s children'
cars: ownersList[FOO]
statement = FOO + " is the owner of the house."
FOO "FOO" 'FOO' "    1 + FOO + 2 " ABCFOOXYZ "  str1\"FOO\"str3'FOO'\'\'" '  str1\'FOOstr3"FOO"\"\"' \"FOO\"`
console.log( text.replace(
  /((?:[^\\]|^)(?:\\{2})*(?:"[^"\\]*(?:\\[^][^"\\]*)*"|'[^'\\]*(?:\\[^][^'\\]*)*'))|FOO/g,
  (match, group) => group || "BAR"
))

Details:

((?:[^\\]|^)(?:\\{2})*(?:"[^"\\]*(?:\\[^][^"\\]*)*"|'[^'\\]*(?:\\[^][^'\\]*)*')) - Group 1:

(?:[^\\]|^) - a char other than \ or start of string

(?:\\{2})* - zero or more sequences of double backslash

(?:"[^"\\]*(?:\\[^][^"\\]*)*"|'[^'\\]*(?:\\[^][^'\\]*)*') - either of a double or single quoted string literal pattern with escape sequence support

| - or

FOO - a FOO string in any other context.

The (match, group) => group || "BAR" replacement means that if Group 1 matches, the replacement is Group 1 value, else, the replacement is BAR.


问:
How to update a value based on previous value in an array of objects?
I am trying to update every current value based on the previous value of another property.

Actually, I need to do the task with dates, but just to keep it simple, I'll explain my problem with simple numbers.

I have

Start, which is 1

Stop, which is already defined

End

Duration, which is already defined

My goal

Start = Duration of previous index + End of previous index

End = Start + Stop of current value

To illustrate, I added the screenshot of the table, how it should look like:

Current view:

Code below and sandbox link

```<code>import React from "react";
import { AgGridReact } from "ag-grid-react";
import "./styles.css";
import "ag-grid-community/dist/styles/ag-grid.css";
import "ag-grid-community/dist/styles/ag-theme-alpine.css";
function App() {
  let start = 1;
  const [gridApi, setGridApi] = React.useState(null);
  const [gridColumnApi, setGridColumnApi] = React.useState(null);

  const onGridReady = (params) => {
    setGridApi(params.api);
    setGridColumnApi(params.columnApi);
  };

  const defaultColDef = {
    flex: 1,
    editable: true
  };

  const columnDefs = [
    {
      headerName: "Name",
      field: "name"
    },
    {
      headerName: "start",
      field: "updatedStart"
    },
    { headerName: "stop", field: "stop" },
    {
      headerName: "end",
      field: "end"
    },
    {
      headerName: "duration",
      field: "duration",
      colId: "duration"
    }
  ];
  const rowData = React.useMemo(
    () => [
      {
        name: "John",
        stop: 10,
        duration: 5
      },
      {
        name: "David",
        stop: 15,
        duration: 8
      },
      {
        name: "Dan",
        stop: 20,
        duration: 6
      }
    ],
    []
  );

  const rowDataWithStart = React.useMemo(() => {
    return (
      rowData &&
      rowData.map((row, i) => ({
        ...row,
        start: start
      }))
    );
  }, [start, rowData]);

  const rowDataWitEnd = React.useMemo(() => {
    return (
      rowDataWithStart &&
      rowDataWithStart.map((row, i) => ({
        ...row,
        end: row.start + row.stop
      }))
    );
  }, [rowDataWithStart]);

//this function(rowDataWitUpdatedStart) should get the previous value of end and duration and get the total
  const rowDataWitUpdatedStart = React.useMemo(() => {
    return (
      rowDataWitEnd &&
      rowDataWitEnd.map((row, i) => ({
        ...row,
        updatedStart: row.end + row.duration
      }))
    );
  }, [rowDataWitEnd]);

  return (
    <div className="App">
      <h1 align="center">React-App</h1>
      <div className="ag-theme-alpine">
        <AgGridReact
          columnDefs={columnDefs}
          rowData={rowDataWitUpdatedStart}
          defaultColDef={defaultColDef}
          domLayout={"autoHeight"}
          onGridReady={onGridReady}
        ></AgGridReact>
      </div>
    </div>
  );
}

export default App;
</code>```

I have tried to do the task making a use of valueGetter from the library I use: AG Grid, but seems to be not the best approach. See my previous question
Any help will be appreciated

答:
Instead of having a step-wise transformation of your data, you can simply do all the operations you want in one go, using Array.prototype.reduce. The way we are going to use Array.prototype.reduce here is going to be almost similar to how you use Array.prototype.map (we are pushing the objects as-is into a new array, so there is no transformation of data), but the advantage is that we have access to the current index in the third argument, which allows us to access values of the previous item in the accumulator.

Array.prototype.map wouldn't work in this case because in each iteration it will not have access to the updated start in the previous item, unless you have a hack-ish way of storing it outside of the function.

With your logic, where you want start to be the duration + end of the previous item, we can use this logic:

```<code>curCopy.start = idx === 0 ? 1 : (acc[idx - 1].duration + acc[idx - 1].end);
</code>```

...which basically says:

If we are on the first item, just start with the seed value of 1 for start

If not, then we access the previous entry (current index minus one) of the accumulator, and access its duration and end properties. Sum them up and use them for start

Use this logic in a new memoized array of objects returned:

```<code>const updatedRowData = React.useMemo(() => {
  const updated = rowData.reduce((acc, cur, idx) => {
    const curCopy =  {...cur};
    const previous = acc[idx - 1];
    curCopy.start = idx === 0 ? 1 : (previous.duration + previous.end);
    curCopy.end = curCopy.start + curCopy.stop;
    acc.push(curCopy);
    return acc;
  }, []);

  return updated;
}, [rowData]);
</code>```

And then in your template, simply use rowData={updatedRowData}.
It should generate the results that you expected:

I have forked your sandbox to create a proof-of-concept example:

Body:
I am trying to update every current value based on the previous value of another property.

Actually, I need to do the task with dates, but just to keep it simple, I'll explain my problem with simple numbers.

I have

Start, which is 1

Stop, which is already defined

End

Duration, which is already defined

My goal

Start = Duration of previous index + End of previous index

End = Start + Stop of current value

To illustrate, I added the screenshot of the table, how it should look like:

Current view:

Code below and sandbox link

import React from "react";
import { AgGridReact } from "ag-grid-react";
import "./styles.css";
import "ag-grid-community/dist/styles/ag-grid.css";
import "ag-grid-community/dist/styles/ag-theme-alpine.css";
function App() {
  let start = 1;
  const [gridApi, setGridApi] = React.useState(null);
  const [gridColumnApi, setGridColumnApi] = React.useState(null);

  const onGridReady = (params) => {
    setGridApi(params.api);
    setGridColumnApi(params.columnApi);
  };

  const defaultColDef = {
    flex: 1,
    editable: true
  };

  const columnDefs = [
    {
      headerName: "Name",
      field: "name"
    },
    {
      headerName: "start",
      field: "updatedStart"
    },
    { headerName: "stop", field: "stop" },
    {
      headerName: "end",
      field: "end"
    },
    {
      headerName: "duration",
      field: "duration",
      colId: "duration"
    }
  ];
  const rowData = React.useMemo(
    () => [
      {
        name: "John",
        stop: 10,
        duration: 5
      },
      {
        name: "David",
        stop: 15,
        duration: 8
      },
      {
        name: "Dan",
        stop: 20,
        duration: 6
      }
    ],
    []
  );

  const rowDataWithStart = React.useMemo(() => {
    return (
      rowData &&
      rowData.map((row, i) => ({
        ...row,
        start: start
      }))
    );
  }, [start, rowData]);

  const rowDataWitEnd = React.useMemo(() => {
    return (
      rowDataWithStart &&
      rowDataWithStart.map((row, i) => ({
        ...row,
        end: row.start + row.stop
      }))
    );
  }, [rowDataWithStart]);

//this function(rowDataWitUpdatedStart) should get the previous value of end and duration and get the total
  const rowDataWitUpdatedStart = React.useMemo(() => {
    return (
      rowDataWitEnd &&
      rowDataWitEnd.map((row, i) => ({
        ...row,
        updatedStart: row.end + row.duration
      }))
    );
  }, [rowDataWitEnd]);

  return (

React-App

        <AgGridReact
          columnDefs={columnDefs}
          rowData={rowDataWitUpdatedStart}
          defaultColDef={defaultColDef}
          domLayout={"autoHeight"}
          onGridReady={onGridReady}
        ></AgGridReact>

  );
}

export default App;

I have tried to do the task making a use of valueGetter from the library I use: AG Grid, but seems to be not the best approach. See my previous question
Any help will be appreciated

Body:
Instead of having a step-wise transformation of your data, you can simply do all the operations you want in one go, using Array.prototype.reduce. The way we are going to use Array.prototype.reduce here is going to be almost similar to how you use Array.prototype.map (we are pushing the objects as-is into a new array, so there is no transformation of data), but the advantage is that we have access to the current index in the third argument, which allows us to access values of the previous item in the accumulator.

Array.prototype.map wouldn't work in this case because in each iteration it will not have access to the updated start in the previous item, unless you have a hack-ish way of storing it outside of the function.

With your logic, where you want start to be the duration + end of the previous item, we can use this logic:

curCopy.start = idx === 0 ? 1 : (acc[idx - 1].duration + acc[idx - 1].end);

...which basically says:

If we are on the first item, just start with the seed value of 1 for start

If not, then we access the previous entry (current index minus one) of the accumulator, and access its duration and end properties. Sum them up and use them for start

Use this logic in a new memoized array of objects returned:

const updatedRowData = React.useMemo(() => {
  const updated = rowData.reduce((acc, cur, idx) => {
    const curCopy =  {...cur};
    const previous = acc[idx - 1];
    curCopy.start = idx === 0 ? 1 : (previous.duration + previous.end);
    curCopy.end = curCopy.start + curCopy.stop;
    acc.push(curCopy);
    return acc;
  }, []);

  return updated;
}, [rowData]);

And then in your template, simply use rowData={updatedRowData}.
It should generate the results that you expected:

I have forked your sandbox to create a proof-of-concept example:


问:
ReactJS - Element type is invalid
I keep getting this weird error in my React that says

```<code>Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Check the render method of `ContactTemplate`.
</code>```

I tried to remove each of the import to see where the error is, but nothing works.

My ContactTemplate.jsx:

```<code>import React from 'react';
import { Container } from '~/components/interface/Container';
import PreviewBar from '~/components/PreviewBar';
import HeroFull from '~/components/HeroFull/HeroFull';
import { Wrapper, Columns, Paragraph, BigText } from './ContactTemplate.styles';
import { Link } from '~/components/interface/Link';

const ContactTemplate = ({ preview }) => {
  const data = [
    {
      name: 'Name 1',
      job: 'Bestuursrechts',
      phone: '+31 (0) 612345678',
      email: 'Email',
      link: 'https://www.linkedin.com',
    },
    {
      name: 'Name 2',
      job: 'Intellectuele eigendom en contractenrecht',
      phone: '+31 (0) 612345678',
      email: 'email',
      link: 'https://www.linkedin.com',
    },
  ];

  return (
    <>
      <Wrapper>
        {preview && <PreviewBar />}
        <HeroFull
          title="Contact"
          intro="We offer ...."
        />
      </Wrapper>
      <Container>
        <Columns>
          {data.map(item => (
            <div>
              <BigText>{item.name}</BigText>
              <Paragraph>{item.job}</Paragraph>
              <Paragraph>{item.phone}</Paragraph>
              <Paragraph>{item.email}</Paragraph>
              <Link>{item.link}</Link>
            </div>
          ))}
        </Columns>
      </Container>
    </>
  );
};

export default ContactTemplate;
</code>```

Could someone help me out with this please?
If there are more files needed I'll add them on request.

答:
Most likely you're trying to import { ContactTemplate } from "./ContactTemplate", but you're using export default. At this point you should import ContactTemplate from "./ContactTemplate"

Can you confirm if this is the case?
Can you show the component, where you import and trying to use ContactTemplate?

Title: ReactJS - Element type is invalid

Body:
I keep getting this weird error in my React that says

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Check the render method of `ContactTemplate`.

I tried to remove each of the import to see where the error is, but nothing works.

My ContactTemplate.jsx:

import React from 'react';
import { Container } from '~/components/interface/Container';
import PreviewBar from '~/components/PreviewBar';
import HeroFull from '~/components/HeroFull/HeroFull';
import { Wrapper, Columns, Paragraph, BigText } from './ContactTemplate.styles';
import { Link } from '~/components/interface/Link';

const ContactTemplate = ({ preview }) => {
  const data = [
    {
      name: 'Name 1',
      job: 'Bestuursrechts',
      phone: '+31 (0) 612345678',
      email: 'Email',
      link: 'https://www.linkedin.com',
    },
    {
      name: 'Name 2',
      job: 'Intellectuele eigendom en contractenrecht',
      phone: '+31 (0) 612345678',
      email: 'email',
      link: 'https://www.linkedin.com',
    },
  ];

  return (
    <>
      <Wrapper>
        {preview && <PreviewBar />}
        <HeroFull
          title="Contact"
          intro="We offer ...."
        />
      </Wrapper>
      <Container>
        <Columns>
          {data.map(item => (

              <BigText>{item.name}</BigText>
              <Paragraph>{item.job}</Paragraph>
              <Paragraph>{item.phone}</Paragraph>
              <Paragraph>{item.email}</Paragraph>
              <Link>{item.link}</Link>

          ))}
        </Columns>
      </Container>
    </>
  );
};

export default ContactTemplate;

Could someone help me out with this please?
If there are more files needed I'll add them on request.


问:
How to install jdk 8 on ubuntu server 18.04?
I am trying to install JDK 8 ON Ubuntu server 18.04 LTS, with the following commands:

```<code>sudo apt install openjdk-8-jre
sudo apt install openjdk-8-jdk
</code>```

/usr/lib/jvm folder has:

I also set the path into /etc/environment for JAVA_HOME
But I still get an error while java -version as:

```<code>Command 'java' not found, but can be installed with:

sudo apt install default-jre
sudo apt install openjdk-11-jre-headless
sudo apt install openjdk-8-jre-headless

</code>```

Can anyone please suggest to solve an error?
Thank you in advance.

答:
Update alternatives for Java. This should fix the problem:

```<code> update-alternatives --config java
</code>```

Reference: https://linoxide.com/install-java-ubuntu/

Body:
I am trying to install JDK 8 ON Ubuntu server 18.04 LTS, with the following commands:

sudo apt install openjdk-8-jre
sudo apt install openjdk-8-jdk

/usr/lib/jvm folder has:

I also set the path into /etc/environment for JAVA_HOME
But I still get an error while java -version as:

Command 'java' not found, but can be installed with:

sudo apt install default-jre
sudo apt install openjdk-11-jre-headless
sudo apt install openjdk-8-jre-headless

Can anyone please suggest to solve an error?
Thank you in advance.

Body:
Update alternatives for Java. This should fix the problem:

 update-alternatives --config java

Reference: https://linoxide.com/install-java-ubuntu/


问:
Select2 ignore certain input?
So I'm using the Select2 JQuery based replacement for select boxes.

I've set it up (with help from an example I found) for remote data searching via ajax which works great. I've got a minimum input value of 3 so the user has to enter at least 3 characters before the search starts (otherwise "A" would return 90% of the searchable values).

Unfortunately a large portion of my searchable values also start with "The". So if a user types "The", 50% of the results get returned, populating a huge dropdown with basically unfiltered results ... not ideal!

Is there any way to get Select2 to ignore certain set phrases, ie typing "The" shouldn't count towards the minimum 3 character count!

```<code>$('#searchInput').select2({
    minimumInputLength: 3,
    placeholder: 'Please search here ...',
    ajax: {
        url: "/api/v1/institutes",
        dataType: 'json',
        quietMillis: 100,
        data: function(term, page) {
            return {
                query: term
            };
        },
        results: function(data, page ) {
            return { results: data }
        }
    },
    formatResult: function(institute) {
        return "<div class='select2-user-result'>" + institute.name + "</div>";
    },
    formatSelection: function(institute) {
        return institute.name;
    },
    initSelection : function (element, callback) {
        var elementText = $(element).attr('data-init-text');
        callback({"term":elementText});
    }
});
</code>```

答:
I faced the same problem. I solved the problem by using "data-minimum-input-length" attribute in html code.</p>
```<code><select id="mySelect" data-minimum-input-length="3"></select>
</code>```

Title: Select2 ignore certain input?

Body:
So I'm using the Select2 JQuery based replacement for select boxes.

I've set it up (with help from an example I found) for remote data searching via ajax which works great. I've got a minimum input value of 3 so the user has to enter at least 3 characters before the search starts (otherwise "A" would return 90% of the searchable values).

Unfortunately a large portion of my searchable values also start with "The". So if a user types "The", 50% of the results get returned, populating a huge dropdown with basically unfiltered results ... not ideal!

Is there any way to get Select2 to ignore certain set phrases, ie typing "The" shouldn't count towards the minimum 3 character count!

$('#searchInput').select2({
    minimumInputLength: 3,
    placeholder: 'Please search here ...',
    ajax: {
        url: "/api/v1/institutes",
        dataType: 'json',
        quietMillis: 100,
        data: function(term, page) {
            return {
                query: term
            };
        },
        results: function(data, page ) {
            return { results: data }
        }
    },
    formatResult: function(institute) {
        return "
" + institute.name + "
";
    },
    formatSelection: function(institute) {
        return institute.name;
    },
    initSelection : function (element, callback) {
        var elementText = $(element).attr('data-init-text');
        callback({"term":elementText});
    }
});

Body:
I faced the same problem. I solved the problem by using "data-minimum-input-length" attribute in html code.

<select id="mySelect" data-minimum-input-length="3"></select>


问:
How can I change the location of a cursor image?

Possible Duplicate:

  Custom cursor interaction point - CSS / JQuery

I am changing the image of the mouse pointer using the CSS cursor property ("cursor: url(images/target.png), crosshair;") and have noticed when a user clicks it takes the point from the top left of the image.

How could I change that to a given x & y point within the cursor image?

edit: Custom cursor interaction point - CSS / JQuery gave me the answer (I guess it makes this a duplicate question) - thanks "mu is too short"

答: Just an idea (dunno if it works): Have you considered using a larger image with some transparent space on the side where you need the offset?</p>


问:
why iPhone .app files is much larger than .ipa file?
My new iPhone application have .ipa file size (by Archive) is 2.8 MB, which is okay.
But my .app file is much large > 13 MB, and AppStore describes my app's size is 7.9 MB.

What causes this problem? Can I make my app size in AppStore is the same as my ipa file?

Thanks,

UPDATE:

When I unzip .ipa file, I see an .app file whose size is 5.2 MB!!!. It seem that I have difference configuration between these build settings. Wonder if I can use this app file to upload (beta tester can use this anyway!)

When I use iTunes to sync my downloaded app from AppStore, the .ipa size is > 13M (same as my uploaded .app)

答: .ipa files are compressed, which explains why they're smaller. I'm not sure why your .app file is so much larger than what the App Store reports unless Apple does some sort of image compression for the App Store.</p>


问:
VBScript [Used to export from one program to the excel]
To summarize what I need, I will start with simple explanation:

I am using .vbs script to export from "E3 Zucken" software to excel template.

One of the exported columns in excel is getting this value which is being pulled from E3 Zucken:

I have, maybe, 10 different wire sizes and the problem is that I need an if statement in .vbs script to detect which wire size is getting pulled and base on the wire size it should set the "font" size according to the wire size.

Currently I have this line in my .vbs script that puts the font size automatically to 5 which is not suitable for all wire sizes that I have:

```<code>Excel.Cells(nline, 50).Value = "5"    '"A1Font"
</code>```

Is it possible to set this value according to the wire size?

答:
A re-usable approach would be to build a function that encapsulates the conditional logic, something like this, by using a Dictionary we can build up a list of wire sizes as keys and the font size as the value of the entry;

```<code>Function DetermineFontSize(wire_size)
    Const default_size = 5
    If Len(wire_size & "") < 1 DetermineFontSize = default_size 'Guard clause
    Dim list: Set list = CreateObject("Scripting.Dictionary")
    Call list.Add("FLRYW-B-0.35_BK", 5)
    ... 'Assumed other entries
    Call list.Add("FLRYW-B-4.00_BK", 7)
    If Not list.Exists(wire_size) Then DetermineFontSize = default_size
    DetermineFontSize = list(wire_size).Value
End Function
</code>```

You would call it by passing the wire size value into the Function.

```<code>Excel.Cells(nline, 50).Value = DetermineFontSize(your_wire_size)
</code>```

Body:
To summarize what I need, I will start with simple explanation:

I am using .vbs script to export from "E3 Zucken" software to excel template.

One of the exported columns in excel is getting this value which is being pulled from E3 Zucken:

I have, maybe, 10 different wire sizes and the problem is that I need an if statement in .vbs script to detect which wire size is getting pulled and base on the wire size it should set the "font" size according to the wire size.

Currently I have this line in my .vbs script that puts the font size automatically to 5 which is not suitable for all wire sizes that I have:

Excel.Cells(nline, 50).Value = "5"    '"A1Font"

Is it possible to set this value according to the wire size?

Body:
A re-usable approach would be to build a function that encapsulates the conditional logic, something like this, by using a Dictionary we can build up a list of wire sizes as keys and the font size as the value of the entry;

Function DetermineFontSize(wire_size)
    Const default_size = 5
    If Len(wire_size & "") < 1 DetermineFontSize = default_size 'Guard clause
    Dim list: Set list = CreateObject("Scripting.Dictionary")
    Call list.Add("FLRYW-B-0.35_BK", 5)
    ... 'Assumed other entries
    Call list.Add("FLRYW-B-4.00_BK", 7)
    If Not list.Exists(wire_size) Then DetermineFontSize = default_size
    DetermineFontSize = list(wire_size).Value
End Function

You would call it by passing the wire size value into the Function.

Excel.Cells(nline, 50).Value = DetermineFontSize(your_wire_size)


问:
Column identification when search on multiple index columns
I'm using supabase(PostgreSQL). I'm using full text search(on multiple columns using indexing) of PostgreSQL and its working fine but i want to get column identification(which means i want to get a column which is populating results.

For example:

column name: name, email, skill, location, indexed_column(in which multiple columns are indexed)

In upper mentioned table i want to search on indexed_column and want to get result with another field(in which field i want a specific column which is populating results)

答:
If you have a single text-search column, for example as a generated column defined with

```<code>tscol GENERATED ALWAYS AS
   (to_tsvector('english', col1) ||
    to_tsvector('english', col2))
   STORED
</code>```

there is no way you can determine from which column the text originated.

What you can do is search for your search string in the individual columns as well:

```<code>SELECT id,
       to_tsvector('english', col1) @@ to_tsquery('english', 'string') AS matches_col1,
       to_tsvector('english', col2) @@ to_tsquery('english', 'string') AS matches_col2,
FROM tab
WHERE tscol @@ to_tsquery('english', 'string');
</code>```

That can still be sped up with a single text search index.

Body:
If you have a single text-search column, for example as a generated column defined with

tscol GENERATED ALWAYS AS
   (to_tsvector('english', col1) ||
    to_tsvector('english', col2))
   STORED

there is no way you can determine from which column the text originated.

What you can do is search for your search string in the individual columns as well:

SELECT id,
       to_tsvector('english', col1) @@ to_tsquery('english', 'string') AS matches_col1,
       to_tsvector('english', col2) @@ to_tsquery('english', 'string') AS matches_col2,
FROM tab
WHERE tscol @@ to_tsquery('english', 'string');

That can still be sped up with a single text search index.