问:
solidity ConnectionError: HTTPConnectionPool(host='0.0.0.0', port=7545) #30
Macbook Pro : Monterey

Intel Core i7

Brownie v1.17.2

I am learning solidity according to reference(https://www.youtube.com/watch?v=M576WGiDBdQ&t=25510s).

At youtube freedcodecamp 5:41:17 ,when tried to deploy to ganache-local,pop out these error information.
before refactoring deployed to ganache UI and rinkeby successfully, and i add ganache-local to brownie network this error pop.

```<code>ConnectionError: HTTPConnectionPool(host='0.0.0.0', port=7545): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fd62639d700>: Failed to establish a new connection: [Errno 61] Connection refused'))

</code>```

full error

```<code>BronieFundMe2022Project is the active project.

Running 'scripts/deploy.py::main'...
The active network is ganache-local
Deploying Mocks....
  File "brownie/_cli/run.py", line 50, in main
    return_value, frame = run(
  File "brownie/project/scripts.py", line 103, in run
    return_value = f_locals[method_name](*args, **kwargs)
  File "./scripts/deploy.py", line 27, in main
    deploy_fund_me()
  File "./scripts/deploy.py", line 16, in deploy_fund_me
    deploy_mocks()
  File "./scripts/helpful_scripts.py", line 20, in deploy_mocks
    MockV3Aggregator.deploy(DECIMALS,Web3.toWei(STARTING_PRICE,"ether"),{"from":get_account()})
  File "brownie/network/contract.py", line 528, in __call__
    return tx["from"].deploy(
  File "brownie/network/account.py", line 510, in deploy
    receipt, exc = self._make_transaction(
  File "brownie/network/account.py", line 720, in _make_transaction
    gas_price, gas_strategy, gas_iter = self._gas_price(gas_price)
  File "brownie/network/account.py", line 456, in _gas_price
    return web3.eth.generate_gas_price(), None, None
  File "web3/eth.py", line 877, in generate_gas_price
    return self._generate_gas_price(transaction_params)
  File "web3/eth.py", line 173, in _generate_gas_price
    return self.gasPriceStrategy(self.web3, transaction_params)
  File "web3/gas_strategies/rpc.py", line 20, in rpc_gas_price_strategy
    return web3.manager.request_blocking(RPC.eth_gasPrice, [])
  File "web3/manager.py", line 197, in request_blocking
    response = self._make_request(method, params)
  File "web3/manager.py", line 150, in _make_request
    return request_func(method, params)
  File "cytoolz/functoolz.pyx", line 250, in cytoolz.functoolz.curry.__call__
  File "web3/middleware/formatting.py", line 76, in apply_formatters
    response = make_request(method, params)
  File "web3/middleware/gas_price_strategy.py", line 90, in middleware
    return make_request(method, params)
  File "cytoolz/functoolz.pyx", line 250, in cytoolz.functoolz.curry.__call__
  File "web3/middleware/formatting.py", line 76, in apply_formatters
    response = make_request(method, params)
  File "web3/middleware/attrdict.py", line 33, in middleware
    response = make_request(method, params)
  File "cytoolz/functoolz.pyx", line 250, in cytoolz.functoolz.curry.__call__
  File "web3/middleware/formatting.py", line 76, in apply_formatters
    response = make_request(method, params)
  File "cytoolz/functoolz.pyx", line 250, in cytoolz.functoolz.curry.__call__
  File "web3/middleware/formatting.py", line 76, in apply_formatters
    response = make_request(method, params)
  File "cytoolz/functoolz.pyx", line 250, in cytoolz.functoolz.curry.__call__
  File "web3/middleware/formatting.py", line 76, in apply_formatters
    response = make_request(method, params)
  File "web3/middleware/buffered_gas_estimate.py", line 40, in middleware
    return make_request(method, params)
  File "web3/middleware/exception_retry_request.py", line 105, in middleware
    return make_request(method, params)
  File "web3/providers/rpc.py", line 88, in make_request
    raw_response = make_post_request(
  File "web3/_utils/request.py", line 48, in make_post_request
    response = session.post(endpoint_uri, data=data, *args, **kwargs)  # type: ignore
  File "requests/sessions.py", line 590, in post
    return self.request('POST', url, data=data, json=json, **kwargs)
  File "requests/sessions.py", line 542, in request
    resp = self.send(prep, **send_kwargs)
  File "requests/sessions.py", line 655, in send
    r = adapter.send(request, **kwargs)
  File "requests/adapters.py", line 516, in send
    raise ConnectionError(e, request=request)
ConnectionError: HTTPConnectionPool(host='0.0.0.0', port=7545): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fd62639d700>: Failed to establish a new connection: [Errno 61] Connection refused'))
</code>```

deploy scripts

```<code>from brownie import FundMe,network,config,MockV3Aggregator
from scripts.helpful_scripts import (deploy_mocks, get_account,LOCAL_BLOCKCHAIN_ENVIRONMENT)

def deploy_fund_me():
    account = get_account()
    # pass the price feed address to our fundme contract

    # if we are on a persistent network like rinkeby, use the associated address
    # otherwise, deploy mocks
    if network.show_active() not in LOCAL_BLOCKCHAIN_ENVIRONMENT:
        price_feed_address = config["network"][network_showactive()]["eth_usd_price_feed"]

    else:
        deploy_mocks()
        price_feed_address = MockV3Aggregator[-1].address

    fund_me = FundMe.deploy(
        price_feed_address,
        {"from":account},
        publish_source=config["networks"][network.show_active()].get("verify"),
        )
    print(f"The contract deploy to {fund_me.address}")

def main():
    deploy_fund_me()
</code>```

答:
Problem fixed by using "brownie networks delete ganache-local" ,then add the network again.
and set the ganache port to 8545, chainid to 1337
and reboot .</p>

Body:
Macbook Pro : Monterey

Intel Core i7

Brownie v1.17.2

I am learning solidity according to reference(https://www.youtube.com/watch?v=M576WGiDBdQ&t=25510s).

At youtube freedcodecamp 5:41:17 ,when tried to deploy to ganache-local,pop out these error information.
before refactoring deployed to ganache UI and rinkeby successfully, and i add ganache-local to brownie network this error pop.

ConnectionError: HTTPConnectionPool(host='0.0.0.0', port=7545): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fd62639d700>: Failed to establish a new connection: [Errno 61] Connection refused'))

full error

BronieFundMe2022Project is the active project.

Running 'scripts/deploy.py::main'...
The active network is ganache-local
Deploying Mocks....
  File "brownie/_cli/run.py", line 50, in main
    return_value, frame = run(
  File "brownie/project/scripts.py", line 103, in run
    return_value = f_locals[method_name](*args, **kwargs)
  File "./scripts/deploy.py", line 27, in main
    deploy_fund_me()
  File "./scripts/deploy.py", line 16, in deploy_fund_me
    deploy_mocks()
  File "./scripts/helpful_scripts.py", line 20, in deploy_mocks
    MockV3Aggregator.deploy(DECIMALS,Web3.toWei(STARTING_PRICE,"ether"),{"from":get_account()})
  File "brownie/network/contract.py", line 528, in __call__
    return tx["from"].deploy(
  File "brownie/network/account.py", line 510, in deploy
    receipt, exc = self._make_transaction(
  File "brownie/network/account.py", line 720, in _make_transaction
    gas_price, gas_strategy, gas_iter = self._gas_price(gas_price)
  File "brownie/network/account.py", line 456, in _gas_price
    return web3.eth.generate_gas_price(), None, None
  File "web3/eth.py", line 877, in generate_gas_price
    return self._generate_gas_price(transaction_params)
  File "web3/eth.py", line 173, in _generate_gas_price
    return self.gasPriceStrategy(self.web3, transaction_params)
  File "web3/gas_strategies/rpc.py", line 20, in rpc_gas_price_strategy
    return web3.manager.request_blocking(RPC.eth_gasPrice, [])
  File "web3/manager.py", line 197, in request_blocking
    response = self._make_request(method, params)
  File "web3/manager.py", line 150, in _make_request
    return request_func(method, params)
  File "cytoolz/functoolz.pyx", line 250, in cytoolz.functoolz.curry.__call__
  File "web3/middleware/formatting.py", line 76, in apply_formatters
    response = make_request(method, params)
  File "web3/middleware/gas_price_strategy.py", line 90, in middleware
    return make_request(method, params)
  File "cytoolz/functoolz.pyx", line 250, in cytoolz.functoolz.curry.__call__
  File "web3/middleware/formatting.py", line 76, in apply_formatters
    response = make_request(method, params)
  File "web3/middleware/attrdict.py", line 33, in middleware
    response = make_request(method, params)
  File "cytoolz/functoolz.pyx", line 250, in cytoolz.functoolz.curry.__call__
  File "web3/middleware/formatting.py", line 76, in apply_formatters
    response = make_request(method, params)
  File "cytoolz/functoolz.pyx", line 250, in cytoolz.functoolz.curry.__call__
  File "web3/middleware/formatting.py", line 76, in apply_formatters
    response = make_request(method, params)
  File "cytoolz/functoolz.pyx", line 250, in cytoolz.functoolz.curry.__call__
  File "web3/middleware/formatting.py", line 76, in apply_formatters
    response = make_request(method, params)
  File "web3/middleware/buffered_gas_estimate.py", line 40, in middleware
    return make_request(method, params)
  File "web3/middleware/exception_retry_request.py", line 105, in middleware
    return make_request(method, params)
  File "web3/providers/rpc.py", line 88, in make_request
    raw_response = make_post_request(
  File "web3/_utils/request.py", line 48, in make_post_request
    response = session.post(endpoint_uri, data=data, *args, **kwargs)  # type: ignore
  File "requests/sessions.py", line 590, in post
    return self.request('POST', url, data=data, json=json, **kwargs)
  File "requests/sessions.py", line 542, in request
    resp = self.send(prep, **send_kwargs)
  File "requests/sessions.py", line 655, in send
    r = adapter.send(request, **kwargs)
  File "requests/adapters.py", line 516, in send
    raise ConnectionError(e, request=request)
ConnectionError: HTTPConnectionPool(host='0.0.0.0', port=7545): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fd62639d700>: Failed to establish a new connection: [Errno 61] Connection refused'))

deploy scripts

from brownie import FundMe,network,config,MockV3Aggregator
from scripts.helpful_scripts import (deploy_mocks, get_account,LOCAL_BLOCKCHAIN_ENVIRONMENT)

def deploy_fund_me():
    account = get_account()
    # pass the price feed address to our fundme contract

    # if we are on a persistent network like rinkeby, use the associated address
    # otherwise, deploy mocks
    if network.show_active() not in LOCAL_BLOCKCHAIN_ENVIRONMENT:
        price_feed_address = config["network"][network_showactive()]["eth_usd_price_feed"]

    else:
        deploy_mocks()
        price_feed_address = MockV3Aggregator[-1].address

    fund_me = FundMe.deploy(
        price_feed_address,
        {"from":account},
        publish_source=config["networks"][network.show_active()].get("verify"),
        )
    print(f"The contract deploy to {fund_me.address}")

def main():
    deploy_fund_me()


来源: stackexchange

问:
Improving a List Comprehension
The list comprehension below achieves the desired result/output:

Each tuple in the list is indexed sequentially

The names are grouped together by suit

The names are in a consistent order

Code (deck of cards toy example):

```<code>Suits = ["Hearts"]*3 +["Diamonds"]*3
Names = ["Two","Ten","King"]

z = [(i,Names[(i-1)%3],Suits[((i-1)%6)]) for i in range(1,7)]
</code>```

Output z:

```<code>[(1, 'Two', 'Hearts'),
 (2, 'Ten', 'Hearts'),
 (3, 'King', 'Hearts'),
 (4, 'Two', 'Diamonds'),
 (5, 'Ten', 'Diamonds'),
 (6, 'King', 'Diamonds')]
</code>```

It works because the original Suits list was changed from ["Hearts","Diamonds"] to["Hearts"]*3 +["Diamonds"]*3.

This feels contrived; although it works, I'm looking for a better solution.

答:
You can use itertools.product and enumerate:

from itertools import product

suits = ["Hearts", "Diamonds"]
sames = ["Two","Ten","King"]

cards = [(index, suit, rank) for index, (suit, rank) in enumerate(product(sames, suits), start=1)]

print(cards)
```

ContentLicense: CC BY-SA 4.0

Title: Improving a List Comprehension

Body:
The list comprehension below achieves the desired result/output:

Each tuple in the list is indexed sequentially

The names are grouped together by suit

The names are in a consistent order

Code (deck of cards toy example):

Suits = ["Hearts"]*3 +["Diamonds"]*3
Names = ["Two","Ten","King"]

z = [(i,Names[(i-1)%3],Suits[((i-1)%6)]) for i in range(1,7)]

Output z:

[(1, 'Two', 'Hearts'),
 (2, 'Ten', 'Hearts'),
 (3, 'King', 'Hearts'),
 (4, 'Two', 'Diamonds'),
 (5, 'Ten', 'Diamonds'),
 (6, 'King', 'Diamonds')]

It works because the original Suits list was changed from ["Hearts","Diamonds"] to["Hearts"]*3 +["Diamonds"]*3.

This feels contrived; although it works, I'm looking for a better solution.


问:
if else statement Mule 3
I want to set a variable based on the output in Mule 3.

For example the check I want to do is if there is any payload
I want to set the var value to this ${http.path.one} else
${http.path.two}.
In Mule 4 it can be done in multiple ways but in Mule 3 seems little tricky. Has anyone an idea how to implement this in Mule 3?

答:
In Mule 3 DataWeave you can use when/otherwise instead of Mule 4 if/else. To access the properties use the p() function. Depending on the exact payload and the condition you need you may need to tweak the expression for the condition.

Example:

p('http.path.two') when (payload != null) otherwise p('http.path.one')
```

Title: if else statement Mule 3


问:
Error using devise_token_auth gem Rails 7
So I'm trying to generate a token for my Rails 7 app with devise_token_auth and I found this gem but I get this error and I understand that the gem is no longer updated:

```<code>Fetchings gem metadata from https://rubygems.org/...........
Resolving dependencies....
Bundler could not finde compatible versions from gem "rails":
    In Gemfile:
        rails (~> 7.0.1)

    devise_token_auth was resolved to 0.1.21.alpha2, which depends on
        rails (~> 4.1.4)
</code>```

So what can I do about it?
Are there more gems like devise_token_auth? I can fix it without chainging my Rails version?

Thanks!

答:
The latest version of devise_token_auth on rubygems (1.2.0) doesn't support rails 7, but the latest code on GitHub does support rails 7.

Try adding the gem like this

```<code>gem 'devise_token_auth', '>= 1.2.0', git: "https://github.com/lynndylanhurley/devise_token_auth"
</code>```

Body:
So I'm trying to generate a token for my Rails 7 app with devise_token_auth and I found this gem but I get this error and I understand that the gem is no longer updated:

Fetchings gem metadata from https://rubygems.org/...........
Resolving dependencies....
Bundler could not finde compatible versions from gem "rails":
    In Gemfile:
        rails (~> 7.0.1)

    devise_token_auth was resolved to 0.1.21.alpha2, which depends on
        rails (~> 4.1.4)

So what can I do about it?
Are there more gems like devise_token_auth? I can fix it without chainging my Rails version?

Thanks!

Body:
The latest version of devise_token_auth on rubygems (1.2.0) doesn't support rails 7, but the latest code on GitHub does support rails 7.

Try adding the gem like this

gem 'devise_token_auth', '>= 1.2.0', git: "https://github.com/lynndylanhurley/devise_token_auth"


问:
how to hide TextFormField based on a value of Radio Button OR DropdownButtonFormField in Flutter
I'm new to Flutter and Dart language and I'm trying so hard to learn it by myself.

So, my question is I have a DropdownButtonFormField with 2 values (private chat and phone number) :

```<code>Widget menu(){
  return DropdownButtonFormField(
    decoration: InputDecoration(
      border: OutlineInputBorder(),
      labelText: 'how to contact with the buyer?',
      labelStyle: TextStyle(
          fontSize: 16,
          color: Colors.grey,
          fontFamily: 'Almarai'
        ),
    ),
  items: <String>['phone number', 'private chat'].map((String value) {
    return DropdownMenuItem<String>(
      value: value,
      child: Text(value),
    );
  }).toList(),
  onChanged: (String newValue) {
    setState(() {
      dropdownvalue = newValue;
    });
  },
);
}
</code>```

And I have this TextFormField that I want it to be hidden if the (private chat) option is selected :

```<code> Widget phonenum(){
    return
          TextFormField(
            maxLength: 10,
            decoration: InputDecoration(
              border: OutlineInputBorder(),
              labelText: 'phone number',
              labelStyle: TextStyle(
                fontSize: 16,
                color: Colors.grey,
                fontFamily: 'Almarai'
              ),
            ),
          );
  }
</code>```

How can I achieve that please? And also, how can I achieve it using RadioButton rather than DropdownButtonFormField ? Because I still didn't decide which one is more suitable with my project flow.

答:
```<code> Widget phonenum(){

    if(dropdownvalue= 'phone number'){
        return TextFormField(
          maxLength: 10,
          decoration: InputDecoration(
            border: OutlineInputBorder(),
            labelText: 'phone number',
            labelStyle: TextStyle(
              fontSize: 16,
              color: Colors.grey,
              fontFamily: 'Almarai'
            ),
          ),
        );
    }else{
           return Container();

          }
  }
</code>```

Body:
I'm new to Flutter and Dart language and I'm trying so hard to learn it by myself.

So, my question is I have a DropdownButtonFormField with 2 values (private chat and phone number) :

Widget menu(){
  return DropdownButtonFormField(
    decoration: InputDecoration(
      border: OutlineInputBorder(),
      labelText: 'how to contact with the buyer?',
      labelStyle: TextStyle(
          fontSize: 16,
          color: Colors.grey,
          fontFamily: 'Almarai'
        ),
    ),
  items: <String>['phone number', 'private chat'].map((String value) {
    return DropdownMenuItem<String>(
      value: value,
      child: Text(value),
    );
  }).toList(),
  onChanged: (String newValue) {
    setState(() {
      dropdownvalue = newValue;
    });
  },
);
}

And I have this TextFormField that I want it to be hidden if the (private chat) option is selected :

 Widget phonenum(){
    return
          TextFormField(
            maxLength: 10,
            decoration: InputDecoration(
              border: OutlineInputBorder(),
              labelText: 'phone number',
              labelStyle: TextStyle(
                fontSize: 16,
                color: Colors.grey,
                fontFamily: 'Almarai'
              ),
            ),
          );
  }

How can I achieve that please? And also, how can I achieve it using RadioButton rather than DropdownButtonFormField ? Because I still didn't decide which one is more suitable with my project flow.


问:
How to append two lists in order into a text file?
Say I have two lists:

```<code>a = [1, 2, 3, 4]

b = [hello, how, iz, life]
</code>```

How can I make a new list c that takes each element in list a and matches it in order to an element in list b? I want the text file to look something like this:

```<code>1 hello
2 how
3 iz
4 life
</code>```

I attempted c.append(a,b), but I got the following error:

```<code>TypeError: list.append() takes exactly one argument (2 given)
</code>```

答:
Try the following:

```<code>a = [1, 2, 3, 4]

b = ["hello", "how", "iz", "life"]

c = zip(a,b)

with open("sample.txt", 'w') as outfile:
    for elem in c:
        outfile.write(str(elem[0]) + " " + elem[1] +"\n")
</code>```

This will output:

```<code>1 hello
2 how
3 iz
4 life
</code>```

to a file called sample.txt.

Edit:
Kelly makes a great point you can just simplify the line as print(*elem, file=outfile). I looked at the docs for print and I was surprised to find that the print function defines a separator for elements given in the *objects argument and ends the line with a newline through default arguments, which provides us with the same desired output.

Body:
Say I have two lists:

a = [1, 2, 3, 4]

b = [hello, how, iz, life]

How can I make a new list c that takes each element in list a and matches it in order to an element in list b? I want the text file to look something like this:

1 hello
2 how
3 iz
4 life

I attempted c.append(a,b), but I got the following error:

TypeError: list.append() takes exactly one argument (2 given)

Body:
Try the following:

a = [1, 2, 3, 4]

b = ["hello", "how", "iz", "life"]

c = zip(a,b)

with open("sample.txt", 'w') as outfile:
    for elem in c:
        outfile.write(str(elem[0]) + " " + elem[1] +"\n")

This will output:

1 hello
2 how
3 iz
4 life

to a file called sample.txt.

Edit:
Kelly makes a great point you can just simplify the line as print(*elem, file=outfile). I looked at the docs for print and I was surprised to find that the print function defines a separator for elements given in the *objects argument and ends the line with a newline through default arguments, which provides us with the same desired output.


问:
Background covering the whole page (CSS)
I just switched from VSC to Adobe Dreamweaver and i don't know if I should keep it or not; but that's besides the point.

When I try to add a background to some text, it fills the whole screen with the background with the background, and if I try to change the width it only adds on to the background which is filling the whole screen.

I don't know if it's user error, something changed in HTML/CSS overnight or if it's because of the Dreamweaver display box thing on the top of my screen

@charset "utf-8";
* {
  margin: 0;
  padding: 0;
}

.Container {
  padding: 25%;
  padding-left: 50%;
  padding-right: 50%;
  font-family: comfortaa;
  font-style: normal;
  font-weight: 600;
  color: white;
  background: #00C3FF;
  margin: 0;
}

body {
  background-image: url(http://www.incomeactivator.com/images/freebg5.jpg);
  background-repeat: no-repeat;
  background-size: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <title>index</title>
  <link href="file:///C|/Users/REDACTED/Documents/style.css" rel="stylesheet" type="text/css">
  <!--The following script tag downloads a font from the Adobe Edge Web Fonts server for use within the web page. We recommend that you do not modify it.-->
  <script>
    var __adobewebfontsappname__ = "dreamweaver"
  </script>
  <script src="http://use.edgefonts.net/comfortaa:n3:default.js" type="text/javascript"></script>

</head>

<body>

  <div class="Container">
    <h1>Hello</h1>
  </div>
</body>

</html></code>```

p.s: let me know if you need a ss of the results I get.

答:
It should work as expected if you apply the css to the H1 tag:

```<code>.Container h1{}
</code>```

You have used padding property incorrectly. Reference

Correct syntax:  padding: top right bottom left

```<code>padding:0 50% 0 50%;
</code>```

So the css should be:

```<code>.Container{ margin: 0; }

.Container h1{
  padding:0 50% 0 50%;
  font-family: comfortaa;
  font-style: normal;
  font-weight: 600;
  color: white;
  background: #00C3FF;
}
</code>```

Body:
I just switched from VSC to Adobe Dreamweaver and i don't know if I should keep it or not; but that's besides the point.

When I try to add a background to some text, it fills the whole screen with the background with the background, and if I try to change the width it only adds on to the background which is filling the whole screen.

I don't know if it's user error, something changed in HTML/CSS overnight or if it's because of the Dreamweaver display box thing on the top of my screen

@charset "utf-8";
* {
  margin: 0;
  padding: 0;
}

.Container {
  padding: 25%;
  padding-left: 50%;
  padding-right: 50%;
  font-family: comfortaa;
  font-style: normal;
  font-weight: 600;
  color: white;
  background: #00C3FF;
  margin: 0;
}

body {
  background-image: url(http://www.incomeactivator.com/images/freebg5.jpg);
  background-repeat: no-repeat;
  background-size: 100%;
}

<!doctype html>

  <meta charset="utf-8">
  <title>index</title>
  <link href="file:///C|/Users/REDACTED/Documents/style.css" rel="stylesheet" type="text/css">

Hello

p.s: let me know if you need a ss of the results I get.

Body:
It should work as expected if you apply the css to the H1 tag:

.Container h1{}

You have used padding property incorrectly. Reference

Correct syntax:  padding: top right bottom left

padding:0 50% 0 50%;

So the css should be:

.Container{ margin: 0; }

.Container h1{
  padding:0 50% 0 50%;
  font-family: comfortaa;
  font-style: normal;
  font-weight: 600;
  color: white;
  background: #00C3FF;
}


问:
MySQL join with conditional "on" statement
Say I have the below 2 tables:

```<code>text

id
</code>```
```<code>text_lang

id
media_id
lang
text
</code>```

(these are not the actual table structures - but I just have 2 tables with one containing all the localized strings that "belong" to the first table)

I want to join the tables, with a "preferred" language. So basically:

```<code>SELECT text.id, text_lang.text
FROM text
         LEFT JOIN text_lang ON text.id = text_lang.text_id
                             AND (only a single row, and if there's a row with lang="en", pick that,
                             otherwise just pick any language)
</code>```

The part I'm having trouble with is the "only a single row, and if there's a row with lang="en" pick that, otherwise just pick any language".

I think this does what I'm looking for:

```<code>SELECT text.id, text_lang.text
FROM text
         JOIN text_lang ON text_lang.text_id = text.id AND
                           text_lang.lang = (select lang
                                             FROM text_lang sub_text_lang
                                             WHERE sub_text_lang.text_id = text.id
                                             ORDER BY text_lang.lang = "en" DESC
                                             limit 1)
</code>```

... but I'd like to avoid a sub-query if possible, as I assume that would be quite a hit to the query performance.

答:
I can think of a few ways but since you're trying to avoid subquery, perhaps you can do something like this:

```<code>SELECT t.id,
       SUBSTRING_INDEX(
          GROUP_CONCAT(text ORDER BY CASE WHEN lang='en' THEN 0 ELSE RAND() END),',',1)
          AS extracted_text
       FROM
       text t
       LEFT JOIN text_lang tl ON tl.text_id=t.id
 GROUP BY t.id;
</code>```

Use GROUP_CONCAT() with a customized ORDER BY then use SUBTRING_INDEX() to get the first value using comma (the default GROUP_CONCAT() separator) as the delimiter.

I've made a fiddle with sample data here: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=0d0501f36af1ba4e181856f761dbd5f7 . You can run the fiddle a few times to see that the text value other than 'en' change.

Body:
Say I have the below 2 tables:

text

id

text_lang

id
media_id
lang
text

(these are not the actual table structures - but I just have 2 tables with one containing all the localized strings that "belong" to the first table)

I want to join the tables, with a "preferred" language. So basically:

SELECT text.id, text_lang.text
FROM text
         LEFT JOIN text_lang ON text.id = text_lang.text_id
                             AND (only a single row, and if there's a row with lang="en", pick that,
                             otherwise just pick any language)

The part I'm having trouble with is the "only a single row, and if there's a row with lang="en" pick that, otherwise just pick any language".

I think this does what I'm looking for:

SELECT text.id, text_lang.text
FROM text
         JOIN text_lang ON text_lang.text_id = text.id AND
                           text_lang.lang = (select lang
                                             FROM text_lang sub_text_lang
                                             WHERE sub_text_lang.text_id = text.id
                                             ORDER BY text_lang.lang = "en" DESC
                                             limit 1)

... but I'd like to avoid a sub-query if possible, as I assume that would be quite a hit to the query performance.

Body:
I can think of a few ways but since you're trying to avoid subquery, perhaps you can do something like this:

SELECT t.id,
       SUBSTRING_INDEX(
          GROUP_CONCAT(text ORDER BY CASE WHEN lang='en' THEN 0 ELSE RAND() END),',',1)
          AS extracted_text
       FROM
       text t
       LEFT JOIN text_lang tl ON tl.text_id=t.id
 GROUP BY t.id;

Use GROUP_CONCAT() with a customized ORDER BY then use SUBTRING_INDEX() to get the first value using comma (the default GROUP_CONCAT() separator) as the delimiter.

I've made a fiddle with sample data here: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=0d0501f36af1ba4e181856f761dbd5f7 . You can run the fiddle a few times to see that the text value other than 'en' change.


问:
International notation for input time format
I have a page that tells the user to input a time in the format hh:mm:ss.  This is obviously fine for English speaking audiences, but is this an acceptable international notation?

If not, could you give me some examples of how other countries display this kind of information to the user.

答: I know dates are different between different country, but time is pretty standard.  you won't have problem with French, spanish, german, UK...  i don't know for asian country tho...</p>

ContentLicense: CC BY-SA 3.0


问:
Google Apps Script Save copy to read only
How do you save a copy of the current Sheets file to a read-only copy? We have scripts that set values that once confirmed save to a new Sheets file. This new file needs to be set as ReadOnly as a part of the script.</p>

答:
In your situation, how about using content protection?

Sample script:

Before you use this script, please enable Drive API at Advanced Google services.

const fileId = "###"; // Please set the file ID. In your situation, please set the Spreadsheet ID.
Drive.Files.patch({contentRestrictions: [{readOnly: true}]}, fileId);
```

When this script is run, the Spreadsheet can be only viewed and the Spreadsheet cannot be written.

If you want to unprotect it, please modify {readOnly: true} to {readOnly: false} in the above script.

References:

Protect file content from modification

Files: patch

Body:
In your situation, how about using content protection?

Sample script:

Before you use this script, please enable Drive API at Advanced Google services.

const fileId = "###"; // Please set the file ID. In your situation, please set the Spreadsheet ID.
Drive.Files.patch({contentRestrictions: [{readOnly: true}]}, fileId);

When this script is run, the Spreadsheet can be only viewed and the Spreadsheet cannot be written.

If you want to unprotect it, please modify {readOnly: true} to {readOnly: false} in the above script.

References:

Protect file content from modification

Files: patch


问:
Gitlab coverage badge from nyc istanbul cobertura xml
i have a public adonis js boilerplate in gitlab and i am struggling with the coverage badge as it shows "unknown"
the repo link: https://gitlab.com/XanXus961/adonis-boilerplate</p>

答:
The coverage badge does not work with the cobertura report but with the coverage keyword.

You should add this to your test job:

  coverage: '/Statements\s*: \d+\.\d+/'
```

It should match this line, Gitlab should do the rest.

Body:
The coverage badge does not work with the cobertura report but with the coverage keyword.

You should add this to your test job:

  coverage: '/Statements\s*: \d+\.\d+/'

It should match this line, Gitlab should do the rest.


问:
`%_` and detecting unwanted named arguments to a method
As I understand, a named argument to a method goes to %_ if not found in the signature (not sure why!). To detect this, I do

```<code>die "Extra args passed" if %_;
</code>```

for the methods I remember to do and that are worth doing. Is there a way to automate this for example with some decorator kind of thing? Or I miss and %_ is actually a very useful thing in object oriented Raku programming?

答:
Is there a way to automate this for example with some decorator kind of thing?

Because this is Raku where there's always More Than One Way To Do It, there are in fact multiple ways to fairly easily prevent the automatic *%_ method parameter.  I'll show you two (and explain how they work) and then try to convince you that, in fact "%_ is actually a very useful thing in object oriented Raku programming".

The answer: rejecting unexpected named parameters (the *%_)

Consider this code:

class C0           { method m        { say 'm called' } }
class C1           { method m(*% ()) { say 'm called' } }
class C2 is hidden { method m        { say 'm called' } }

my $c = C0.new;
$c.m(:unexpected); # OUTPUT: «m called»
```
<p><code>C0</code> is a standard class and, as you've already noted, it happily accepts unexpected named arguments.  But if we try the same thing with <code>C1</code>, we'd get this error:</p>
```Unexpected named argument 'unexpected' passed in sub-signature
```
<p>And, if we tried it with <code>C2</code>, we'd get this very similar one:</p>
```Unexpected named argument 'unexpected' passed
```
<p>The biggest difference for our current purposes is that <code>C1</code> just disallowed unexpected named arguments for <code>m</code> – we could create other <code>C1</code> methods that <em>do</em> accept unexpected named arguments.  Conversely, with <code>C2</code>, we prevent <em>any</em> of the classes methods from accepting unexpected named arguments (and do a bit more, but more on that soon).</p>
<h3>How do these each work?</h3>
<h4>C1</h4>
<p><code>C1</code> prevents <code>m</code> from accepting any unexpected arguments by using named slurpy parameter and then destructuring that parameter into a sub-signature – in this case, a sub-signature that happens to consist of an empty list.</p>
<p>Breaking that down a bit, consider this code:</p>
<pre class="lang-raku prettyprint-override"><code>sub f(:$group-name!, *@ids (Int, Int?, Int?, Int?) {}
</code>```

That signature is saying "I have to have a :group-name parameter and some number of @ids.  And those @ids must have at least one Int, and could have up to four Ints – but no more than four, and no non-Ints)".  So we can call f with :group-name<foo>, 1.  Or with :group-name<foo>, 1, 42, 55.  But if we tried to call it with :group-name<foo>, 1, 42, 55, 9, 9, 9, we'd get the error: Too many positionals passed to 'f'; expected 1 to 4 arguments but got 6 in sub-signature of parameter @ids.

So what's the signature in C1's m method saying.  Well, the *% part says "I'll take a list of absolutely any named argument at all" and then the  () part adds "so long as that list doesn't have anything in it!".

And that gets us exactly what you were looking for: a method that rejects unexpected named arguments (and expected named arguments don't pose any problem at all – you'd declare those before the *%, and they'd be handled before ever reaching the sub-signature.

C2

C2 is both simpler and, at the same time, a bit more overkill.  C2 uses the hidden trait which stops C2 from participating in the redistpatch process – and, as a side effect, prevents C2's methods from being given an automatic *%_ parameter.

Explaining the full scope of Raku's (re) dispatch process is beyond the scope of this answer but I'll just say that, depending on what you want, that may be exactly what you're looking for or it may be an unwanted consequence.

But you should (maybe) ignore those answers

Let's go back to how you ended your ques ion.  You asked whether you missed something that makes *%_ "actually a very useful thing in object oriented Raku programming".  I'd argue that, yes, the automatic addition of *%_ is in fact very helpful.

There are a bunch of different ways to come at why that's the case but, since you mentioned object-oriented Raku, I'll come at it from that angle (I personally write more functional-programming Raku, but the both have there place).

So from an OOP perspective, the addition of *%_ makes it much easier to write Raku methods that follow the Liskov_substitution_principle (aka, the L in SOLID OOP).

I'm not sure how familiar you are with that principle, so I'll say just a few words about it (apologizes if I'm belaboring the obvious).  The LSP says that "Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program".

That can be a bit abstract, so here's a Raku example that's … ok, still kind of abstract, but bear with me.

So, consider the Raku Stash class.  It doesn't matter what it does right now; I'm bringing it up because of its type graph:

So a Stash isa Hash and a Hash isa Map and a Map isa Cool and a Cool isa Mu.  So that means that any function that's type-constrained with any of Stash, Hash, Map, Cool, or Mu will accept a Stash – and it's up to Stash to make sure that it can be validly passed to any such function without breaking anything.  Of course, for the most part a Stash handles this through inheritance: most of the methods that you can call on a Stash aren't actually defined on the Stash – they're inherited and thus are automatically compatible with the superclass method (because they are the superclass method).

But, for methods that Stash chooses to overwrite, it's part of Stash's job to make sure that it doesn't break any superclasses expected behavior.  And the same goes for, say, Map – but even more so.  If there's a method on Cool that Map overrides, Map needs to think not only about Map's callers but also about Stash's callers: after all, Stash might not override that method.   So Map needs to make sure that it can handle anything Cool wants/needs to handle – and that's something that, in theory, could happen at any time.  (In practice, of course, Cool is pretty stable and both it and Map are part of Rakudo.  But the same thing would apply for 3rd-party classes, where APIs change more rapidly and you may not have the ability to coordinate changes.)

In particular, "handling anything Cool can handle" means being able to be called with the arguments callers of Cool passed without throwing type errors – even when those arguments might change.

And that's where *%_ comes in.  Unless one of them opts out, every member of the method chain accepts any named parameter.  As a result, Cool can freely add new named parameters, and Map/Stash's callers (who, after all, aren't supposed to care or need to care whether which object they're calling) can pass in the corresponding named arguments. And, even if those method calls get resolved by a method that's never heard of the new argument, absolutely nothing will break.

Of course, if it just gets eaten by *%_, the new argument won't actually do anything, which (depending on the class/method) might not be ideal.  But that's where re-dispatching comes back in and lets the intervening class act on the method and still pass it on to a superclass.  But, again, that's getting out of scope.

So, after a long answer to a short question, the bottom line is that you can prevent a method from accepting unexpected named arguments.  But, depending on your approach to programming/Raku, there are some very good reasons to consider not doing so.

Body:
As I understand, a named argument to a method goes to %_ if not found in the signature (not sure why!). To detect this, I do

die "Extra args passed" if %_;

for the methods I remember to do and that are worth doing. Is there a way to automate this for example with some decorator kind of thing? Or I miss and %_ is actually a very useful thing in object oriented Raku programming?

Body:
Is there a way to automate this for example with some decorator kind of thing?

Because this is Raku where there's always More Than One Way To Do It, there are in fact multiple ways to fairly easily prevent the automatic *%_ method parameter.  I'll show you two (and explain how they work) and then try to convince you that, in fact "%_ is actually a very useful thing in object oriented Raku programming".

The answer: rejecting unexpected named parameters (the *%_)

Consider this code:

class C0           { method m        { say 'm called' } }
class C1           { method m(*% ()) { say 'm called' } }
class C2 is hidden { method m        { say 'm called' } }

my $c = C0.new;
$c.m(:unexpected); # OUTPUT: «m called»

C0 is a standard class and, as you've already noted, it happily accepts unexpected named arguments.  But if we try the same thing with C1, we'd get this error:

Unexpected named argument 'unexpected' passed in sub-signature

And, if we tried it with C2, we'd get this very similar one:

Unexpected named argument 'unexpected' passed

The biggest difference for our current purposes is that C1 just disallowed unexpected named arguments for m – we could create other C1 methods that do accept unexpected named arguments.  Conversely, with C2, we prevent any of the classes methods from accepting unexpected named arguments (and do a bit more, but more on that soon).

How do these each work?

C1

C1 prevents m from accepting any unexpected arguments by using named slurpy parameter and then destructuring that parameter into a sub-signature – in this case, a sub-signature that happens to consist of an empty list.

Breaking that down a bit, consider this code:

sub f(:$group-name!, *@ids (Int, Int?, Int?, Int?) {}

That signature is saying "I have to have a :group-name parameter and some number of @ids.  And those @ids must have at least one Int, and could have up to four Ints – but no more than four, and no non-Ints)".  So we can call f with :group-name<foo>, 1.  Or with :group-name<foo>, 1, 42, 55.  But if we tried to call it with :group-name<foo>, 1, 42, 55, 9, 9, 9, we'd get the error: Too many positionals passed to 'f'; expected 1 to 4 arguments but got 6 in sub-signature of parameter @ids.

So what's the signature in C1's m method saying.  Well, the *% part says "I'll take a list of absolutely any named argument at all" and then the  () part adds "so long as that list doesn't have anything in it!".

And that gets us exactly what you were looking for: a method that rejects unexpected named arguments (and expected named arguments don't pose any problem at all – you'd declare those before the *%, and they'd be handled before ever reaching the sub-signature.

C2

C2 is both simpler and, at the same time, a bit more overkill.  C2 uses the hidden trait which stops C2 from participating in the redistpatch process – and, as a side effect, prevents C2's methods from being given an automatic *%_ parameter.

Explaining the full scope of Raku's (re) dispatch process is beyond the scope of this answer but I'll just say that, depending on what you want, that may be exactly what you're looking for or it may be an unwanted consequence.

But you should (maybe) ignore those answers

Let's go back to how you ended your ques ion.  You asked whether you missed something that makes *%_ "actually a very useful thing in object oriented Raku programming".  I'd argue that, yes, the automatic addition of *%_ is in fact very helpful.

There are a bunch of different ways to come at why that's the case but, since you mentioned object-oriented Raku, I'll come at it from that angle (I personally write more functional-programming Raku, but the both have there place).

So from an OOP perspective, the addition of *%_ makes it much easier to write Raku methods that follow the Liskov_substitution_principle (aka, the L in SOLID OOP).

I'm not sure how familiar you are with that principle, so I'll say just a few words about it (apologizes if I'm belaboring the obvious).  The LSP says that "Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program".

That can be a bit abstract, so here's a Raku example that's … ok, still kind of abstract, but bear with me.

So, consider the Raku Stash class.  It doesn't matter what it does right now; I'm bringing it up because of its type graph:

So a Stash isa Hash and a Hash isa Map and a Map isa Cool and a Cool isa Mu.  So that means that any function that's type-constrained with any of Stash, Hash, Map, Cool, or Mu will accept a Stash – and it's up to Stash to make sure that it can be validly passed to any such function without breaking anything.  Of course, for the most part a Stash handles this through inheritance: most of the methods that you can call on a Stash aren't actually defined on the Stash – they're inherited and thus are automatically compatible with the superclass method (because they are the superclass method).

But, for methods that Stash chooses to overwrite, it's part of Stash's job to make sure that it doesn't break any superclasses expected behavior.  And the same goes for, say, Map – but even more so.  If there's a method on Cool that Map overrides, Map needs to think not only about Map's callers but also about Stash's callers: after all, Stash might not override that method.   So Map needs to make sure that it can handle anything Cool wants/needs to handle – and that's something that, in theory, could happen at any time.  (In practice, of course, Cool is pretty stable and both it and Map are part of Rakudo.  But the same thing would apply for 3rd-party classes, where APIs change more rapidly and you may not have the ability to coordinate changes.)

In particular, "handling anything Cool can handle" means being able to be called with the arguments callers of Cool passed without throwing type errors – even when those arguments might change.

And that's where *%_ comes in.  Unless one of them opts out, every member of the method chain accepts any named parameter.  As a result, Cool can freely add new named parameters, and Map/Stash's callers (who, after all, aren't supposed to care or need to care whether which object they're calling) can pass in the corresponding named arguments. And, even if those method calls get resolved by a method that's never heard of the new argument, absolutely nothing will break.

Of course, if it just gets eaten by *%_, the new argument won't actually do anything, which (depending on the class/method) might not be ideal.  But that's where re-dispatching comes back in and lets the intervening class act on the method and still pass it on to a superclass.  But, again, that's getting out of scope.

So, after a long answer to a short question, the bottom line is that you can prevent a method from accepting unexpected named arguments.  But, depending on your approach to programming/Raku, there are some very good reasons to consider not doing so.


问:
Switch from PHP to Java or .Net
I currently run a website on LAMP, I am currently in the process of refactoring my code from normal php to Zend framework with Doctrine. I am happy with setup but often find function not found errors on live site cause I have renamed function. Which is frustrating as most of time is wasted is patching these errors.
So I have decided to switch from php to java as the code gets compiled, so just error will not go to live site. With java netbeans will work better.

But as I have not been in touch to j2ee for many years. What is the best replacement for my above setup in java?

Option 1. Jsf 2 with Hibernate

Option 2. Seam

Option 3. Spring

Option 4. Struts with Hibernate

My server has 24 gig ram and 2 core i7 processor and ssd drive on raid 0

Will my server handle the same amount of visitors if java was used without any performance issues?

I like the way I can update my site without losing live sessions(logged-in users). Can I do the same in Java? from my experience each update to site will redeploy the App which resets all the Active Sessions.

I love to consider .Net but from what I have read on most forums, no one recommends it?

Kind regards

Zerone

答: You problem is not switching to Java from PHP your problem is an good test coverage via unit and in particular with integration tests. From what you wrote the best thing might be to take a look at Selenium and to automate testing as most as possible. You need a complete infrastructure to deploy to a test system and run integration tests on it (Selenium) and after that you can say everything is ok.</p>

Title: Switch from PHP to Java or .Net


问:
What does a method signature look like in a NEAR contract that recieves a JSON Array of objects with undeployed structs?
I am looking to receive Proposal data from a Sputnik v2 DAO Contract. I want to call get_proposals but that returns a json list of the proposals. I am unsure as to what the method signature on the callback function would look like to receive the data. Since sputnik-dao-contract is not a published Rust Crate, I cannot import the Proposal struct and use it to deserialize. What is the best approach to processing the response and getting the Proposal id?

Here is the method I want to call:
https://github.com/near-daos/sputnik-dao-contract#view-multiple-proposals

How to I recieve, deserialize and use the response programmatically in Rust?

答:
If the get_proposals method already returns a list of proposals, aren't you already getting what you need? I mean, the data is in the response. If you need a proposal on a specific ID, you can always use another function, get_proposal instead.

From the response, the struct looks simple enough that you can create it on your own. You can copy the Proposal struct directly from the repo as well.

```<code>/// Proposal that are sent to this DAO.
#[derive(BorshSerialize, BorshDeserialize, Serialize, Deserialize)]
#[cfg_attr(not(target_arch = "wasm32"), derive(Debug))]
#[serde(crate = "near_sdk::serde")]
pub struct Proposal {
    /// Original proposer.
    pub proposer: AccountId,
    /// Description of this proposal.
    pub description: String,
    /// Kind of proposal with relevant information.
    pub kind: ProposalKind,
    /// Current status of the proposal.
    pub status: ProposalStatus,
    /// Count of votes per role per decision: yes / no / spam.
    pub vote_counts: HashMap<String, [Balance; 3]>,
    /// Map of who voted and how.
    pub votes: HashMap<AccountId, Vote>,
    /// Submission time (for voting period).
    pub submission_time: U64,
}
</code>```

Body:
If the get_proposals method already returns a list of proposals, aren't you already getting what you need? I mean, the data is in the response. If you need a proposal on a specific ID, you can always use another function, get_proposal instead.

From the response, the struct looks simple enough that you can create it on your own. You can copy the Proposal struct directly from the repo as well.

/// Proposal that are sent to this DAO.
#[derive(BorshSerialize, BorshDeserialize, Serialize, Deserialize)]
#[cfg_attr(not(target_arch = "wasm32"), derive(Debug))]
#[serde(crate = "near_sdk::serde")]
pub struct Proposal {
    /// Original proposer.
    pub proposer: AccountId,
    /// Description of this proposal.
    pub description: String,
    /// Kind of proposal with relevant information.
    pub kind: ProposalKind,
    /// Current status of the proposal.
    pub status: ProposalStatus,
    /// Count of votes per role per decision: yes / no / spam.
    pub vote_counts: HashMap<String, [Balance; 3]>,
    /// Map of who voted and how.
    pub votes: HashMap<AccountId, Vote>,
    /// Submission time (for voting period).
    pub submission_time: U64,
}


问:
Get string from tkinter text object without line break
I'm trying to create a basic tkinter app where I prompt the user for a query and it outputs to to an excel file but when I try to get the value of the userinput I always get a linebreak. How do I avoid this?

```<code>...
Textinput = Text(app,width=68,height=5,yscrollcommand=sb2.set)
Textinput.grid(row=3,column=0,columnspan=colSpan,sticky=N)
compareButton = Button(text="Output to XLSX",command = lambda: exportToExcel(Textinput.get("1.0","end")))
...
</code>```

Should I be using something other than "end" for the get command?
I have a workaround, but would prefer to solve the issue at its source.

Thank you!

答:
Add .strip() at the end of the get method:

Button(text="Output to XLSX",command = lambda: pressing(Textinput.get("1.0","end").strip())).grid()
```
<p>Or as @jasonharper suggested, use <code>Entry</code>:</p>
<pre class="lang-py prettyprint-override"><code>Textinput = Entry(app,width=68,height=5)
Textinput.grid(row=3,column=0,columnspan=1,sticky=N)
</code>```

Body:
I'm trying to create a basic tkinter app where I prompt the user for a query and it outputs to to an excel file but when I try to get the value of the userinput I always get a linebreak. How do I avoid this?

...
Textinput = Text(app,width=68,height=5,yscrollcommand=sb2.set)
Textinput.grid(row=3,column=0,columnspan=colSpan,sticky=N)
compareButton = Button(text="Output to XLSX",command = lambda: exportToExcel(Textinput.get("1.0","end")))
...

Should I be using something other than "end" for the get command?
I have a workaround, but would prefer to solve the issue at its source.

Thank you!

Body:
Add .strip() at the end of the get method:

Button(text="Output to XLSX",command = lambda: pressing(Textinput.get("1.0","end").strip())).grid()

Or as @jasonharper suggested, use Entry:

Textinput = Entry(app,width=68,height=5)
Textinput.grid(row=3,column=0,columnspan=1,sticky=N)


问:
Is there any way to get this order by query to start searching from the given timestamp on a MySQL index?
I am working on a mysql 5.6 database, and I have a table looking something like this:

```<code>CREATE TABLE `items` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `account_id` int(11) NOT NULL,
  `node_type_id` int(11) NOT NULL,
  `property_native_id` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `parent_item_id` bigint(20) DEFAULT NULL,
  `external_timestamp` datetime DEFAULT NULL,
  `created_at` datetime DEFAULT NULL,
  `updated_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `index_items_on_acct_node_prop` (`account_id`,`node_type_id`,`property_native_id`),
  KEY `index_items_on_account_id_and_external_timestamp` (`account_id`,`external_timestamp`),
  KEY `index_items_on_account_id_and_created_at` (`account_id`,`created_at`),
  KEY `parent_item_external_timestamp_idx` (`parent_item_id`,`external_timestamp`),
) ENGINE=InnoDB AUTO_INCREMENT=194417315 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
</code>```

I am trying to optimize a query doing this:

```<code>SELECT *
FROM items
WHERE parent_item_id = ?
AND external_timestamp < ( SELECT external_timestamp
                           FROM items
                           WHERE id = ?
                          ) FROM items ORDER BY
external_timestamp LIMIT 5
</code>```

Currently, there is an index on parent_item_id, so when I run this query with EXPLAIN, I get an "extra" of "Using where; Using filesort"

When I modify the index to be (parent_item_id, external_timestamp), then the EXPLAIN's "extra" becomes "Using index condition"

The problem is that the EXPLAIN's "rows" field is still the same (which is usually a couple thousand rows, but it could be millions in some use-cases).

I know that I can do something like AND external_timestamp > (1 week ago) or something like that, but I'd really like the number of rows to be just the number of LIMIT, so 5 in that case.

Is it possible to instruct the database to lock onto a row and then get the 5 rows before it on that (parent_item_id, external_timestamp) index?

答:
(I'm unclear on what you are trying to do.  Perhaps you should provide some sample input and output.)  See if this works for you:

```<code>SELECT i.*
    FROM items AS i
    WHERE i.parent_item_id = ?
      AND i.external_timestamp < ( SELECT external_timestamp
              FROM items
              WHERE id = ? )
    ORDER BY i.external_timestamp
    LIMIT 5
</code>```

Your existing INDEX(parent_item_id, external_timestamp) will probably be used; see EXPLAIN SELECT ....

If id was supposed to match in all 5 rows, then the subquery is not needed.

Body:
I am working on a mysql 5.6 database, and I have a table looking something like this:

CREATE TABLE `items` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `account_id` int(11) NOT NULL,
  `node_type_id` int(11) NOT NULL,
  `property_native_id` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `parent_item_id` bigint(20) DEFAULT NULL,
  `external_timestamp` datetime DEFAULT NULL,
  `created_at` datetime DEFAULT NULL,
  `updated_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `index_items_on_acct_node_prop` (`account_id`,`node_type_id`,`property_native_id`),
  KEY `index_items_on_account_id_and_external_timestamp` (`account_id`,`external_timestamp`),
  KEY `index_items_on_account_id_and_created_at` (`account_id`,`created_at`),
  KEY `parent_item_external_timestamp_idx` (`parent_item_id`,`external_timestamp`),
) ENGINE=InnoDB AUTO_INCREMENT=194417315 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

I am trying to optimize a query doing this:

SELECT *
FROM items
WHERE parent_item_id = ?
AND external_timestamp < ( SELECT external_timestamp
                           FROM items
                           WHERE id = ?
                          ) FROM items ORDER BY
external_timestamp LIMIT 5

Currently, there is an index on parent_item_id, so when I run this query with EXPLAIN, I get an "extra" of "Using where; Using filesort"

When I modify the index to be (parent_item_id, external_timestamp), then the EXPLAIN's "extra" becomes "Using index condition"

The problem is that the EXPLAIN's "rows" field is still the same (which is usually a couple thousand rows, but it could be millions in some use-cases).

I know that I can do something like AND external_timestamp > (1 week ago) or something like that, but I'd really like the number of rows to be just the number of LIMIT, so 5 in that case.

Is it possible to instruct the database to lock onto a row and then get the 5 rows before it on that (parent_item_id, external_timestamp) index?

Body:
(I'm unclear on what you are trying to do.  Perhaps you should provide some sample input and output.)  See if this works for you:

SELECT i.*
    FROM items AS i
    WHERE i.parent_item_id = ?
      AND i.external_timestamp < ( SELECT external_timestamp
              FROM items
              WHERE id = ? )
    ORDER BY i.external_timestamp
    LIMIT 5

Your existing INDEX(parent_item_id, external_timestamp) will probably be used; see EXPLAIN SELECT ....

If id was supposed to match in all 5 rows, then the subquery is not needed.


问:
SQL Server stored procedure
I want it to count then if @intcount > 0 it should show data or else no data found, but when I execute it gives me 'no data found' regardless, what am I doing wrong?

```<code>@FiscalYear int,
@SchoolID int,
@Status int

AS
BEGIN

SET NOCOUNT ON;

declare @sqlstr varchar(2000)
declare @intCount int
set @intCount = 0

set @sqlstr = 'Select @intCount = Count(*)
              From PrivateSchool left outer join Attachment on  Attachment.PrivateSchoolID = PrivateSchool.PrivateSchoolID
              inner join FiscalYearPrivateSchool fp ON  fp.PrivateSchoolID = PrivateSchool.PrivateSchoolID
              Where (FiscalYear = '+convert(varchar, @FiscalYear)+') AND (PrivateSchool.IsActive = 1)'

 IF (@SchoolID != -1)
    SET @sqlstr = @sqlstr + ' AND SchoolID ='+ convert(varchar, @SchoolID)

 IF (@Status = -1)
    SET @sqlstr = @sqlstr + ' AND PrivateSchool.PrivateSchoolID = PrivateSchool.PrivateSchoolID'

 Else IF (@Status = 1)
    SET @sqlstr = @sqlstr + ' AND Attachment.PrivateSchoolID = PrivateSchool.PrivateSchoolID'
 Else
    SET @sqlstr = @sqlstr + ' AND Attachment.PrivateSchoolID is Null'

 If (@intCount > 0)
 BEGIN
 set @sqlstr=   'Select SchoolName as School,
 (Case when Attachment.PrivateSchoolID = PrivateSchool.PrivateSchoolID THEN ''Uploaded''
  ELSE ''Not Uploaded'' END) AS Status,
  COUNT(Attachment.PrivateSchoolID) AS [Count]
              From PrivateSchool left outer join Attachment on  Attachment.PrivateSchoolID = PrivateSchool.PrivateSchoolID
              inner join FiscalYearPrivateSchool fp ON  fp.PrivateSchoolID = PrivateSchool.PrivateSchoolID
              Where (FiscalYear = '+convert(varchar, @FiscalYear)+') AND (PrivateSchool.IsActive = 1)'

 IF (@SchoolID != -1)
    SET @sqlstr = @sqlstr + ' AND SchoolID ='+ convert(varchar, @SchoolID)

 IF (@Status = -1)
    SET @sqlstr = @sqlstr + ' AND PrivateSchool.PrivateSchoolID = PrivateSchool.PrivateSchoolID'

 Else IF (@Status = 1)
    SET @sqlstr = @sqlstr + ' AND Attachment.PrivateSchoolID = PrivateSchool.PrivateSchoolID'
 Else
    SET @sqlstr = @sqlstr + ' AND Attachment.PrivateSchoolID is Null'

    SET @sqlstr = @sqlstr + ' Group by SchoolName, Attachment.PrivateSchoolID, PrivateSchool.PrivateSchoolID'
    SET @sqlstr = @sqlstr + ' Order By SchoolName'
EXEC(@sqlstr)
 END
 ELSE
 Select 'No Data Found' as 'FileUpload'
 END
</code>```

答:
Your issue is one of scope. The EXEC(@sqlstr) command doesn't have access to the @intcount variable in your stored procedure. I would bet if you ran this code in a query window, it would tell you to declare @intcount.

Listen to YUCK and rewrite this to avoid dynamic SQL, and then your SELECT will be able to set the @intcount variable.

Title: SQL Server stored procedure

Body:
I want it to count then if @intcount > 0 it should show data or else no data found, but when I execute it gives me 'no data found' regardless, what am I doing wrong?

@FiscalYear int,
@SchoolID int,
@Status int

AS
BEGIN

SET NOCOUNT ON;

declare @sqlstr varchar(2000)
declare @intCount int
set @intCount = 0

set @sqlstr = 'Select @intCount = Count(*)
              From PrivateSchool left outer join Attachment on  Attachment.PrivateSchoolID = PrivateSchool.PrivateSchoolID
              inner join FiscalYearPrivateSchool fp ON  fp.PrivateSchoolID = PrivateSchool.PrivateSchoolID
              Where (FiscalYear = '+convert(varchar, @FiscalYear)+') AND (PrivateSchool.IsActive = 1)'

 IF (@SchoolID != -1)
    SET @sqlstr = @sqlstr + ' AND SchoolID ='+ convert(varchar, @SchoolID)

 IF (@Status = -1)
    SET @sqlstr = @sqlstr + ' AND PrivateSchool.PrivateSchoolID = PrivateSchool.PrivateSchoolID'

 Else IF (@Status = 1)
    SET @sqlstr = @sqlstr + ' AND Attachment.PrivateSchoolID = PrivateSchool.PrivateSchoolID'
 Else
    SET @sqlstr = @sqlstr + ' AND Attachment.PrivateSchoolID is Null'

 If (@intCount > 0)
 BEGIN
 set @sqlstr=   'Select SchoolName as School,
 (Case when Attachment.PrivateSchoolID = PrivateSchool.PrivateSchoolID THEN ''Uploaded''
  ELSE ''Not Uploaded'' END) AS Status,
  COUNT(Attachment.PrivateSchoolID) AS [Count]
              From PrivateSchool left outer join Attachment on  Attachment.PrivateSchoolID = PrivateSchool.PrivateSchoolID
              inner join FiscalYearPrivateSchool fp ON  fp.PrivateSchoolID = PrivateSchool.PrivateSchoolID
              Where (FiscalYear = '+convert(varchar, @FiscalYear)+') AND (PrivateSchool.IsActive = 1)'

 IF (@SchoolID != -1)
    SET @sqlstr = @sqlstr + ' AND SchoolID ='+ convert(varchar, @SchoolID)

 IF (@Status = -1)
    SET @sqlstr = @sqlstr + ' AND PrivateSchool.PrivateSchoolID = PrivateSchool.PrivateSchoolID'

 Else IF (@Status = 1)
    SET @sqlstr = @sqlstr + ' AND Attachment.PrivateSchoolID = PrivateSchool.PrivateSchoolID'
 Else
    SET @sqlstr = @sqlstr + ' AND Attachment.PrivateSchoolID is Null'

    SET @sqlstr = @sqlstr + ' Group by SchoolName, Attachment.PrivateSchoolID, PrivateSchool.PrivateSchoolID'
    SET @sqlstr = @sqlstr + ' Order By SchoolName'
EXEC(@sqlstr)
 END
 ELSE
 Select 'No Data Found' as 'FileUpload'
 END


问:
What is the best way to pass an object's data from one page to another in Ionic?
I am trying to pass user data from my main page component to a details page component. I am currently mapping the user data in to a custom Ionic Component. When the custom component is clicked on in the main page, I need it to send the user data to the detail page and render the detail page using the data passed in from the main page.

Main.tsx:

```<code>const userAPILink: string = "https://randomuser.me/api/";
const usersToRender: number = 5;

const Main: React.FC<RouteComponentProps> = ({ history }) => {
  interface IUser {
    data: {
      name: string;
      email: string;
      icon: string;
      country: string;
    };
  }
  const [userList, setUserList] = useState<IUser[]>([]);

  useEffect(() => {
    for (let i = 0; i < usersToRender; ++i) {
      (async () => {
        const res = await axios.get(userAPILink);
        let tempUser: IUser = {
          data: {
            name: `${res.data.results[0].name.first} ${res.data.results[0].name.last}`,
            email: `${res.data.results[0].email}`,
            icon: `${res.data.results[0].picture.thumbnail}`,
            country: `${res.data.results[0].location.country}`,
          },
        };
        setUserList((userList) => {
          return [...userList, tempUser];
        });
      })();
    }
  }, []);

  return (
    <IonPage>
      <IonHeader>
        <IonToolbar mode="ios">
          <IonIcon slot="end" ios={optionsOutline} />
          <IonButtons slot="start">
            <IonMenuButton />
          </IonButtons>
          <IonTitle className="ionTextCenter">LOGO</IonTitle>
        </IonToolbar>
      </IonHeader>

      <IonContent fullscreen className="ionPadding">
        <IonHeader collapse="condense"></IonHeader>
        <IonSegment>
          <IonSegmentButton>Tab 1</IonSegmentButton>
          <IonSegmentButton>Tab 2</IonSegmentButton>
          <IonSegmentButton>Tab 3</IonSegmentButton>
        </IonSegment>
        <IonList>
          {userList.map((user, index) => {
            return (
              <IonItem
                key={index}
                onClick={(e) => {
                  e.preventDefault();
                  history.push({
                    pathname: `/detail/${user.data.name}`,
                    state: [
                      user.data.name,
                      user.data.email,
                      user.data.icon,
                      user.data.country,
                    ],
                  });
                }}
              >
                <UserCard id={index} data={user.data}></UserCard>
              </IonItem>
            );
          })}
        </IonList>
      </IonContent>
    </IonPage>
  );
};

export default Main;

</code>```

UserCard.tsx

```<code>type UserCardProps = {
  id: number,
  data: {
    name: string;
    icon: string;
    email: string;
    country: string;
  };
};

class UserCard extends React.Component<UserCardProps> {
  render() {
    return (
      <IonCard
        // routerLink={`detail/${this.props.data.name}`}
        id={this.props.data.name}
      >
        <IonCardHeader className="card-header">
          <IonGrid>
            <IonRow>
              <IonCol size="3">
                <IonAvatar>
                  <img src={this.props.data.icon} />
                </IonAvatar>
              </IonCol>
              <IonCol size="9">
                <IonCardTitle>{this.props.data.name}</IonCardTitle>
                <IonCardSubtitle>{this.props.data.email}</IonCardSubtitle>
              </IonCol>
            </IonRow>
          </IonGrid>
        </IonCardHeader>
        <IonCardContent>
          <IonText>
            <IonLabel>{this.props.data.country}</IonLabel>
          </IonText>
          <IonImg className="character-img"></IonImg>
          Lorem Ipsum is simply dummy text of the printing and typesetting
          industry. Lorem Ipsum has been the industry's standard dummy text ever
          since the 1500s, when an unknown printer took a galley of type and
          scrambled it to make a type specimen book.
        </IonCardContent>
      </IonCard>
    );
  }
}

export default ({
  id,
  data,
}:

{
  id: number
  data: {
    name: string;
    icon: string;
    email: string;
    country: string;
  };
}) => (
  <UserCard
    id={id}
    data={data}
  ></UserCard>
);
</code>```

Detail.tsx

```<code>interface DetailProps extends RouteComponentProps<{
  name: string;
  country: string;
  email: string;
  icon: string;
}> {}

const Detail: React.FC <DetailProps> = ({match, history}) => {
  return (
    <IonPage>
      <DetailComponent id={3} name="Bob" email="email" country="canada" icon="icon" />
    </IonPage>
  );
};

export default Detail;
</code>```

DetailComponent.tsx

```<code>type DetailItemProps = {
  id: number;
  name: string;
  icon: string;
  email: string;
  country: string;
};

class DetailItem extends React.Component<DetailItemProps> {
  render() {
    return (
      <IonHeader>
        <IonToolbar mode="ios">
          <IonIcon slot="end" ios={optionsOutline} />
          <IonButtons slot="start">
            <IonMenuButton />
          </IonButtons>
          <IonTitle className="ionTextCenter">{this.props.name}</IonTitle>
        </IonToolbar>
      </IonHeader>
    );
  }
}

export default ({
  id,
  name,
  icon,
  email,
  country,
}: {
  id: number;
  name: string;
  icon: string;
  email: string;
  country: string;
}) => (
  <DetailItem
    id={id}
    name={name}
    icon={icon}
    email={email}
    country={country}
  ></DetailItem>
);
</code>```

答:
Assuming the Detail component is being rendered by a Route or otherwise receiving route props (history, location, and match) then it should destructure the location object from props and access the passed route state and pass along the user data as props to the DetailComponent.

```<code>const Detail: React.FC <DetailProps> = ({ location }) => {
  const { state } = location;
  const { country, email, icon, name } = state || {};

  return (
    <IonPage>
      <DetailComponent
        country={country}
        email={email}
        icon={icon}
        id={3}
        name={name}
      />
    </IonPage>
  );
};
</code>```

Body:
I am trying to pass user data from my main page component to a details page component. I am currently mapping the user data in to a custom Ionic Component. When the custom component is clicked on in the main page, I need it to send the user data to the detail page and render the detail page using the data passed in from the main page.

Main.tsx:

const userAPILink: string = "https://randomuser.me/api/";
const usersToRender: number = 5;

const Main: React.FC<RouteComponentProps> = ({ history }) => {
  interface IUser {
    data: {
      name: string;
      email: string;
      icon: string;
      country: string;
    };
  }
  const [userList, setUserList] = useState<IUser[]>([]);

  useEffect(() => {
    for (let i = 0; i < usersToRender; ++i) {
      (async () => {
        const res = await axios.get(userAPILink);
        let tempUser: IUser = {
          data: {
            name: `${res.data.results[0].name.first} ${res.data.results[0].name.last}`,
            email: `${res.data.results[0].email}`,
            icon: `${res.data.results[0].picture.thumbnail}`,
            country: `${res.data.results[0].location.country}`,
          },
        };
        setUserList((userList) => {
          return [...userList, tempUser];
        });
      })();
    }
  }, []);

  return (
    <IonPage>
      <IonHeader>
        <IonToolbar mode="ios">
          <IonIcon slot="end" ios={optionsOutline} />
          <IonButtons slot="start">
            <IonMenuButton />
          </IonButtons>
          <IonTitle className="ionTextCenter">LOGO</IonTitle>
        </IonToolbar>
      </IonHeader>

      <IonContent fullscreen className="ionPadding">
        <IonHeader collapse="condense"></IonHeader>
        <IonSegment>
          <IonSegmentButton>Tab 1</IonSegmentButton>
          <IonSegmentButton>Tab 2</IonSegmentButton>
          <IonSegmentButton>Tab 3</IonSegmentButton>
        </IonSegment>
        <IonList>
          {userList.map((user, index) => {
            return (
              <IonItem
                key={index}
                onClick={(e) => {
                  e.preventDefault();
                  history.push({
                    pathname: `/detail/${user.data.name}`,
                    state: [
                      user.data.name,
                      user.data.email,
                      user.data.icon,
                      user.data.country,
                    ],
                  });
                }}
              >
                <UserCard id={index} data={user.data}></UserCard>
              </IonItem>
            );
          })}
        </IonList>
      </IonContent>
    </IonPage>
  );
};

export default Main;

UserCard.tsx

type UserCardProps = {
  id: number,
  data: {
    name: string;
    icon: string;
    email: string;
    country: string;
  };
};

class UserCard extends React.Component<UserCardProps> {
  render() {
    return (
      <IonCard
        // routerLink={`detail/${this.props.data.name}`}
        id={this.props.data.name}
      >
        <IonCardHeader className="card-header">
          <IonGrid>
            <IonRow>
              <IonCol size="3">
                <IonAvatar>

                </IonAvatar>
              </IonCol>
              <IonCol size="9">
                <IonCardTitle>{this.props.data.name}</IonCardTitle>
                <IonCardSubtitle>{this.props.data.email}</IonCardSubtitle>
              </IonCol>
            </IonRow>
          </IonGrid>
        </IonCardHeader>
        <IonCardContent>
          <IonText>
            <IonLabel>{this.props.data.country}</IonLabel>
          </IonText>
          <IonImg className="character-img"></IonImg>
          Lorem Ipsum is simply dummy text of the printing and typesetting
          industry. Lorem Ipsum has been the industry's standard dummy text ever
          since the 1500s, when an unknown printer took a galley of type and
          scrambled it to make a type specimen book.
        </IonCardContent>
      </IonCard>
    );
  }
}

export default ({
  id,
  data,
}:

{
  id: number
  data: {
    name: string;
    icon: string;
    email: string;
    country: string;
  };
}) => (
  <UserCard
    id={id}
    data={data}
  ></UserCard>
);

Detail.tsx

interface DetailProps extends RouteComponentProps<{
  name: string;
  country: string;
  email: string;
  icon: string;
}> {}

const Detail: React.FC <DetailProps> = ({match, history}) => {
  return (
    <IonPage>
      <DetailComponent id={3} name="Bob" email="email" country="canada" icon="icon" />
    </IonPage>
  );
};

export default Detail;

DetailComponent.tsx

type DetailItemProps = {
  id: number;
  name: string;
  icon: string;
  email: string;
  country: string;
};

class DetailItem extends React.Component<DetailItemProps> {
  render() {
    return (
      <IonHeader>
        <IonToolbar mode="ios">
          <IonIcon slot="end" ios={optionsOutline} />
          <IonButtons slot="start">
            <IonMenuButton />
          </IonButtons>
          <IonTitle className="ionTextCenter">{this.props.name}</IonTitle>
        </IonToolbar>
      </IonHeader>
    );
  }
}

export default ({
  id,
  name,
  icon,
  email,
  country,
}: {
  id: number;
  name: string;
  icon: string;
  email: string;
  country: string;
}) => (
  <DetailItem
    id={id}
    name={name}
    icon={icon}
    email={email}
    country={country}
  ></DetailItem>
);

Body:
Assuming the Detail component is being rendered by a Route or otherwise receiving route props (history, location, and match) then it should destructure the location object from props and access the passed route state and pass along the user data as props to the DetailComponent.

const Detail: React.FC <DetailProps> = ({ location }) => {
  const { state } = location;
  const { country, email, icon, name } = state || {};

  return (
    <IonPage>
      <DetailComponent
        country={country}
        email={email}
        icon={icon}
        id={3}
        name={name}
      />
    </IonPage>
  );
};


问:
NA not permitted in predictors. missForest
I am using missForest in order to impute missing data. I have the data as a data frame and when I put it into the missForest function I get the error:

Error in randomForest.default(x = obsX, y = obsY, ntree = ntree, mtry = mtry,  :  NA not permitted in predictors

However, since I do not have predictors I am just trying to impute I do not know where this comes from. The code below should reproduce the problem with a sample data set.

The code below is a simulated version of my problem. However, I have already tried to convert Y into a data frame and I get the same error.

```<code>Y <- prodNA(matrix(as.character(runif(100) > 0.5), nrow=10))
missForest(Y)
</code>```

答: You need that your variables are factor type, do the transformation and try again</p>

Body:
I am using missForest in order to impute missing data. I have the data as a data frame and when I put it into the missForest function I get the error:

Error in randomForest.default(x = obsX, y = obsY, ntree = ntree, mtry = mtry,  :  NA not permitted in predictors

However, since I do not have predictors I am just trying to impute I do not know where this comes from. The code below should reproduce the problem with a sample data set.

The code below is a simulated version of my problem. However, I have already tried to convert Y into a data frame and I get the same error.

Y <- prodNA(matrix(as.character(runif(100) > 0.5), nrow=10))
missForest(Y)


问:
Adjust the length of facet_wrap so that each facet reflect number of samples?
I have a plot that looks like below. However as you can see facet 4 only has 1 sample but the vertical size is equal to facet 6 which has 4 samples; this makes the plot look really weird since it becomes really thick. I can't use face_grid (facet_grid( cyl~. ,  scales = "free", space="free"  )) at the moment because because then the labels goes to the side but what I really want is to put the labels on top like with facet_wrap as illustrated below. Is there anyway around this? thanks.

```<code> temp = head ( mtcars )
    temp$car = row.names ( temp )

    ggplot( temp  , aes(x=car , y=hp, fill=vs   )) +
      geom_bar(stat = 'identity', position = 'stack') +
      theme_bw() +
      theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
            panel.background = element_blank(), axis.line = element_line(colour = "black"))+
      coord_flip() +
      scale_y_continuous(expand = expansion(mult = c(0, .1))) +

      facet_wrap( ~cyl , ncol=1,  scales = "free"  )
</code>```

答:
Not sure if you want this. If so, you can use facet_col from the package ggforce, which allows you to have facet in a single column and also drop the facet ratio (space argument).

```<code>library(tidyverse)
library(ggforce)

temp = head (mtcars)
temp$car = row.names(temp)

ggplot(temp, aes(x = car , y = hp, fill = vs)) +
  geom_bar(stat = 'identity', position = 'stack') +
  theme_bw() +
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
        panel.background = element_blank(), axis.line = element_line(colour = "black"))+
  coord_flip() +
  scale_y_continuous(expand = expansion(mult = c(0, .1))) +
  ggforce::facet_col(cyl ~ ., scales = "free", space = "free")
</code>```

Body:
I have a plot that looks like below. However as you can see facet 4 only has 1 sample but the vertical size is equal to facet 6 which has 4 samples; this makes the plot look really weird since it becomes really thick. I can't use face_grid (facet_grid( cyl~. ,  scales = "free", space="free"  )) at the moment because because then the labels goes to the side but what I really want is to put the labels on top like with facet_wrap as illustrated below. Is there anyway around this? thanks.

 temp = head ( mtcars )
    temp$car = row.names ( temp )

    ggplot( temp  , aes(x=car , y=hp, fill=vs   )) +
      geom_bar(stat = 'identity', position = 'stack') +
      theme_bw() +
      theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
            panel.background = element_blank(), axis.line = element_line(colour = "black"))+
      coord_flip() +
      scale_y_continuous(expand = expansion(mult = c(0, .1))) +

      facet_wrap( ~cyl , ncol=1,  scales = "free"  )

Body:
Not sure if you want this. If so, you can use facet_col from the package ggforce, which allows you to have facet in a single column and also drop the facet ratio (space argument).

library(tidyverse)
library(ggforce)

temp = head (mtcars)
temp$car = row.names(temp)

ggplot(temp, aes(x = car , y = hp, fill = vs)) +
  geom_bar(stat = 'identity', position = 'stack') +
  theme_bw() +
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
        panel.background = element_blank(), axis.line = element_line(colour = "black"))+
  coord_flip() +
  scale_y_continuous(expand = expansion(mult = c(0, .1))) +
  ggforce::facet_col(cyl ~ ., scales = "free", space = "free")


问:
For what is css.php in cakephp
In webroot i found a file called css.php. Can someone tell me why is this used for.
I have no clue what is this used for i did check the .htacess and that too didn't give me any clue.</p>

答:
It's for combining your CSS files into one downloadable file for the user. That reduces http requests and speeds up the page load. Read here:

http://bakery.cakephp.org/articles/morrislaptop/2008/06/23/combine-your-js-css-files-for-faster-loading

Title: For what is css.php in cakephp


问:
Call a method from inside of subscribe
Im trying to call a method from inside of subscribe in angular/ionic. But its not working. Here is my code:</p>
```<code>somemethod()
{
  const browser = this.iab.create('https://someurl.com');
  browser.on('loadstart').subscribe(event=>{
    if(event.url === 'https://specificurl.com'){
      browser.close();
 // trying to call a member method from here , working
this.mymethod();
    }
  });
  browser.on('exit').subscribe(eventx=>{
   // trying to call a member method from here
this.mymethod();
});
}
mymethod()
{
http.get<any>(url).subscribe(e=> {
this.myvar = e.response; // this data is shown to user, but the user interface is not changing until something is clicked by the user
});
}
</code>```

答:
Just in case... You create the in app browser for url https://someurl.com but you subscribe and check for https://specificurl.com. What if you change it to listen for what you create?

if(event.url == 'https://someurl.com'){
      console.log(event)
      browser.close();
    }
```
<p>If the block itself is reachable go over the scope. Example:</p>
<pre class="lang-js prettyprint-override"><code>@Component({
  templateUrl: 'app.html',
})
export class MyApp {
  rootPage: any = TabsPage;
  response$: Observable<any>;

  constructor(platform: Platform) {
    platform.ready().then(() => {
      this.myMethod();
    });
  }
  myMethod() {
    console.log('cool');
    // TODO supply valid url and other params if neccessary
    this.response$ = http.get<any>(url).pipe(data => {return data;})
  }
}
</code>```

Then use response$ like so:

```<code><div>{{ response$ | async}}</div>
</code>```

https://stackblitz.com/edit/ionic-p5qfps?file=app%2Fapp.component.ts

Title: Call a method from inside of subscribe

Body:
Im trying to call a method from inside of subscribe in angular/ionic. But its not working. Here is my code:

somemethod()
{
  const browser = this.iab.create('https://someurl.com');
  browser.on('loadstart').subscribe(event=>{
    if(event.url === 'https://specificurl.com'){
      browser.close();
 // trying to call a member method from here , working
this.mymethod();
    }
  });
  browser.on('exit').subscribe(eventx=>{
   // trying to call a member method from here
this.mymethod();
});
}
mymethod()
{
http.get<any>(url).subscribe(e=> {
this.myvar = e.response; // this data is shown to user, but the user interface is not changing until something is clicked by the user
});
}

Body:
Just in case... You create the in app browser for url https://someurl.com but you subscribe and check for https://specificurl.com. What if you change it to listen for what you create?

if(event.url == 'https://someurl.com'){
      console.log(event)
      browser.close();
    }

If the block itself is reachable go over the scope. Example:

@Component({
  templateUrl: 'app.html',
})
export class MyApp {
  rootPage: any = TabsPage;
  response$: Observable<any>;

  constructor(platform: Platform) {
    platform.ready().then(() => {
      this.myMethod();
    });
  }
  myMethod() {
    console.log('cool');
    // TODO supply valid url and other params if neccessary
    this.response$ = http.get<any>(url).pipe(data => {return data;})
  }
}

Then use response$ like so:

<div>{{ response$ | async}}</div>

https://stackblitz.com/edit/ionic-p5qfps?file=app%2Fapp.component.ts


问:
Is that possible to deploy Laravel web application to shared hosting using GitHub Action & GitHub FTP Deploy?
Is that possible to deploy the Laravel web application to shared hosting using GitHub Action & GitHub FTP Deploy? If possible how should I change the.github\workflows\master.yml?

```<code>on:
  push:
    branches:
      - master
name:  Deploy website on push
jobs:
  web-deploy:
    name:  Deploy
    runs-on: ubuntu-latest
    steps:
    - name:  Get latest code
      uses: actions/checkout@v2

    - name:  Sync files
      uses: SamKirkland/FTP-Deploy-Action@4.2.0
      with:
        server: ${{ secrets.ftp_server }}
        username: ${{ secrets.ftp_username }}
        password: ${{ secrets.ftp_password }}
        server-dir: /
</code>```

答:
Looks like you're very close but are missing 2 important steps: set up a temporary PHP environment, and use that environment to install your dependencies (Composer).

GitHub Actions Setup

This guide assumes you have a working Laravel installation, a GitHub account, and a shared hosting account that you can access via FTP using a username/password.

I found this video https://www.youtube.com/watch?v=UNWIXYSZfZY helpful to get a basic understanding of how to deploy a simple application. To make this answer helpful to a wider range of people, I'll give a quick outline of my setup. There really aren't any Laravel specific steps.

Workflow directory set up

Create the directories .github\workflows at the root of your project. In the workflows directory, create a yml file named after the branch you want to push to your shared hosting account. Ex. master.yml, staging.yml, development.yml etc. If you only have a single branch then just create one file. The name is important and should match the name of the branch.

Design your workflow

This is very dependent on your project but assuming you have a basic Laravel application without the need for additional components such as Node, then this is a basic GitHub Action that works for me on a variety of projects.

A basic action file consists of 2 sections, the workflow, and the jobs. A workflow triggers the jobs.

Workflow

Lines 1-4 say this will run each time we push to the master branch.

```<code>on:
  push:
    branches:
      - master
</code>```

Line 5 is the name of this workflow and will show up on your Actions page. Set this to something descriptive.

```<code>name:  Deploy website on push (Master)
</code>```

Setting up jobs

In this action, there are 5 jobs. Some take parameters, others don't. I'm not going to explain all the details here but have linked to the corresponding repositories if you need details.

Checkout your code so the workflow has access to it,
https://github.com/actions/checkout

```<code>name:  Get latest code
uses: actions/checkout@v2
</code>```

Sets up a temporary PHP environment so you can run things like
Composer, https://github.com/shivammathur/setup-php. Make sure to set your PHP version here otherwise you could run into issues when installing Composer packages with an unexpected PHP version.

```<code>name: Setup PHP
uses: shivammathur/setup-php@v2
with:
  php-version: 7.2
</code>```

Caches your dependencies for faster deploys,
https://github.com/actions/cache

```<code>name: Cache Composer packages
id: composer-cache
uses: actions/cache@v2
with:
  path: vendor
  key: ${{ runner.os }}-php-${{ hashFiles('**/composer.lock') }}
  restore-keys: |
    ${{ runner.os }}-php-
</code>```

Install your dependencies from composer.json and composer.lock
files.

```<code>name: Install dependencies
run: composer install --prefer-dist --no-progress
</code>```

Deploys your code to your remote shared hosting site,
https://github.com/SamKirkland/FTP-Deploy-Action. Note the use of ${{ secrets.ftp_username }} and ${{ secrets.ftp_password }}. These are set up in your repository's secrets section. See https://docs.github.com/en/actions/security-guides/encrypted-secrets

```<code>name:  Sync files
uses: SamKirkland/FTP-Deploy-Action@4.0.0
with:
  server: name_of_server.com
  username: ${{ secrets.ftp_username }}
  password: ${{ secrets.ftp_password }}
  server-dir: public_html/
</code>```

Final file

```<code>on:
  push:
    branches:
      - master
name:  Deploy website on push (Master)
jobs:
  web-deploy:
    name:  Deploy
    runs-on: ubuntu-latest
    steps:
      - name:  Get latest code
        uses: actions/checkout@v2

      - name: Setup PHP
        uses: shivammathur/setup-php@v2
        with:
          php-version: 7.2

      - name: Cache Composer packages
        id: composer-cache
        uses: actions/cache@v2
        with:
          path: vendor
          key: ${{ runner.os }}-php-${{ hashFiles('**/composer.lock') }}
          restore-keys: |
            ${{ runner.os }}-php-

      - name: Install dependencies
        run: composer install --prefer-dist --no-progress

      - name:  Sync files
        uses: SamKirkland/FTP-Deploy-Action@4.0.0
        with:
          server: name_of_server.com
          username: ${{ secrets.ftp_username }}
          password: ${{ secrets.ftp_password }}
          server-dir: public_html/
</code>```

Running the workflow

Check-in .github\workflows\master.yml, and others if appropriate,
into your GitHub repository. Without these files checked in nothing
will happen when you push a change to the branch.

Go to your Actions tab and ensure the workflow shows up there.

Push a change to your branch and watch the Actions tab. Click into
the running action to see details about the run.

Fix any errors that show up in the console.

Finally, you mentioned in a comment something about NPM. If you have Node as a component in your project you can simply run two extra steps that will bundle your assets and will get deployed along with the rest of the code.

Good luck!

Body:
Is that possible to deploy the Laravel web application to shared hosting using GitHub Action & GitHub FTP Deploy? If possible how should I change the.github\workflows\master.yml?

on:
  push:
    branches:
      - master
name:  Deploy website on push
jobs:
  web-deploy:
    name:  Deploy
    runs-on: ubuntu-latest
    steps:
    - name:  Get latest code
      uses: actions/checkout@v2

    - name:  Sync files
      uses: SamKirkland/FTP-Deploy-Action@4.2.0
      with:
        server: ${{ secrets.ftp_server }}
        username: ${{ secrets.ftp_username }}
        password: ${{ secrets.ftp_password }}
        server-dir: /

Body:
Looks like you're very close but are missing 2 important steps: set up a temporary PHP environment, and use that environment to install your dependencies (Composer).

GitHub Actions Setup

This guide assumes you have a working Laravel installation, a GitHub account, and a shared hosting account that you can access via FTP using a username/password.

I found this video https://www.youtube.com/watch?v=UNWIXYSZfZY helpful to get a basic understanding of how to deploy a simple application. To make this answer helpful to a wider range of people, I'll give a quick outline of my setup. There really aren't any Laravel specific steps.

Workflow directory set up

Create the directories .github\workflows at the root of your project. In the workflows directory, create a yml file named after the branch you want to push to your shared hosting account. Ex. master.yml, staging.yml, development.yml etc. If you only have a single branch then just create one file. The name is important and should match the name of the branch.

Design your workflow

This is very dependent on your project but assuming you have a basic Laravel application without the need for additional components such as Node, then this is a basic GitHub Action that works for me on a variety of projects.

A basic action file consists of 2 sections, the workflow, and the jobs. A workflow triggers the jobs.

Workflow

Lines 1-4 say this will run each time we push to the master branch.

on:
  push:
    branches:
      - master

Line 5 is the name of this workflow and will show up on your Actions page. Set this to something descriptive.

name:  Deploy website on push (Master)

Setting up jobs

In this action, there are 5 jobs. Some take parameters, others don't. I'm not going to explain all the details here but have linked to the corresponding repositories if you need details.

Checkout your code so the workflow has access to it,
https://github.com/actions/checkout

name:  Get latest code
uses: actions/checkout@v2

Sets up a temporary PHP environment so you can run things like
Composer, https://github.com/shivammathur/setup-php. Make sure to set your PHP version here otherwise you could run into issues when installing Composer packages with an unexpected PHP version.

name: Setup PHP
uses: shivammathur/setup-php@v2
with:
  php-version: 7.2

Caches your dependencies for faster deploys,
https://github.com/actions/cache

name: Cache Composer packages
id: composer-cache
uses: actions/cache@v2
with:
  path: vendor
  key: ${{ runner.os }}-php-${{ hashFiles('**/composer.lock') }}
  restore-keys: |
    ${{ runner.os }}-php-

Install your dependencies from composer.json and composer.lock
files.

name: Install dependencies
run: composer install --prefer-dist --no-progress

Deploys your code to your remote shared hosting site,
https://github.com/SamKirkland/FTP-Deploy-Action. Note the use of ${{ secrets.ftp_username }} and ${{ secrets.ftp_password }}. These are set up in your repository's secrets section. See https://docs.github.com/en/actions/security-guides/encrypted-secrets

name:  Sync files
uses: SamKirkland/FTP-Deploy-Action@4.0.0
with:
  server: name_of_server.com
  username: ${{ secrets.ftp_username }}
  password: ${{ secrets.ftp_password }}
  server-dir: public_html/

Final file

on:
  push:
    branches:
      - master
name:  Deploy website on push (Master)
jobs:
  web-deploy:
    name:  Deploy
    runs-on: ubuntu-latest
    steps:
      - name:  Get latest code
        uses: actions/checkout@v2

      - name: Setup PHP
        uses: shivammathur/setup-php@v2
        with:
          php-version: 7.2

      - name: Cache Composer packages
        id: composer-cache
        uses: actions/cache@v2
        with:
          path: vendor
          key: ${{ runner.os }}-php-${{ hashFiles('**/composer.lock') }}
          restore-keys: |
            ${{ runner.os }}-php-

      - name: Install dependencies
        run: composer install --prefer-dist --no-progress

      - name:  Sync files
        uses: SamKirkland/FTP-Deploy-Action@4.0.0
        with:
          server: name_of_server.com
          username: ${{ secrets.ftp_username }}
          password: ${{ secrets.ftp_password }}
          server-dir: public_html/

Running the workflow

Check-in .github\workflows\master.yml, and others if appropriate,
into your GitHub repository. Without these files checked in nothing
will happen when you push a change to the branch.

Go to your Actions tab and ensure the workflow shows up there.

Push a change to your branch and watch the Actions tab. Click into
the running action to see details about the run.

Fix any errors that show up in the console.

Finally, you mentioned in a comment something about NPM. If you have Node as a component in your project you can simply run two extra steps that will bundle your assets and will get deployed along with the rest of the code.

Good luck!