问:
How can I properly query a database multiple times for a value if the first time it didn't find anything C#
I'm building a Car Management app using Xamarin, and my Back End is an ASP.NET Web API. I have a large dataset of cars where I can find the price of the car by Make, Name, Year, Odometer and Engine Capacity. I have tried to average most of the values so I can find data, but many times it just doesn't return anything. So I decided to try and query the database multiple times, but each time it doesn't return anything, I either turn a value into an interval (eg. odometer = 100000 and then odometer >= 80000 && odometer <= 120000). It kinda works like this, but I don't think it's the right way to write it. I was thinking about Strategy Pattern, but can't figure out how to apply in my case.

What I have tried is to make Repository where I get the car object, and then I have six methods that just query the database, each gradually with fewer parameters. There are a lot of If Elses.

public GetCarPriceResponse GetPrice(GetCarPriceRequest car)
        {
            var price = new GetCarPriceResponse
            {
                Errors = new List<string>()
            };

            if (GetPriceFirst(car) == null)
                if (GetPriceSecond(car) == null)
                    if (GetPriceThird(car) == null)
                        if (GetPriceFourth(car) == null)
                            if (GetPriceFifth(car) == null)
                                if (GetPriceSixth(car) == null)
                                {
                                    price.Success = false;
                                    price.Errors.Add("Could not find car
price");
                                }
                                else
                                {
                                    price = GetPriceSixth(car);
                                }
                            else price = GetPriceFifth(car);
                        else price = GetPriceFourth(car);
                    else price = GetPriceThird(car);
                else price = GetPriceSecond(car);
            else price = GetPriceFirst(car);

            price.Success = true;

            return price;
        }
```

<p>The first function looks like this:</p>

```public GetCarPriceResponse GetPriceFirst(GetCarPriceRequest car)
        {
            var prices = _context.CarPrices.Where(p =>
                p.make == car.make &&
                p.model == car.model &&
                p.year == car.year &&
                p.CC == car.CC &&
                p.odometer == car.odometer).ToList();

            if (prices.Count == 0) return null;
            return CalculateAveragePrice(prices);
        }
```

<p>And the third one like this:</p>

```public GetCarPriceResponse GetPriceThird(GetCarPriceRequest car)
        {
            var differenceDown = 0;
            var differenceUp = 0;

            if (car.odometer < 50000)
            {
                differenceDown = 0;
                differenceUp = 50000;
            }
            else if (car.odometer > 50000)
            {
                differenceDown = 50000;
                differenceUp = 50000;
            }
            else if (car.odometer > 215000)
            {
                differenceDown = 50000;
                differenceUp = 0;
            }

            var prices = _context.CarPrices.Where(p =>
                p.make == car.make &&
                p.model == car.model &&
                p.year == car.year &&
                p.CC == car.CC &&
                p.odometer >= car.odometer - differenceDown &&
                p.odometer <= car.odometer + differenceUp).ToList();

            if (prices.Count == 0) return null;
            return CalculateAveragePrice(prices);
        }
```

<p>In the fourth one I completely eliminate the odometer parameter, and in the sixth one I query a different database that has an average price based on odometer, engine capacity and model year.
This is the fifth method:</p>

``` public GetCarPriceResponse GetPriceFifth(GetCarPriceRequest car)
        {
            var prices = _context.CarPrices.Where(p =>
                p.make == car.make &&
                p.model == car.model &&
                p.year >= car.year - 2 &&
                p.year <= car.year + 2 &&
                p.CC == car.CC).ToList();

            if (prices.Count == 0) return null;
            return CalculateAveragePrice(prices);
        }
```

It works fine for now, but for example if you add an electric car, with the engine capacity of 0, it does not function properly and such.
But I am asking if there is a way to make this code better.

Thank you.

答:
Instead of trying to find a single car each time have the query return a list of cars that match make, model, year and CC (since that seems to be the common criteria) and sort the results by odometer value.  Your app can then look through the list (using a local LINQ query) to find the best match in the list.

Trying to query for a single match multiple times is going to be way too slow due to all of the network traffic.

Body:
I'm building a Car Management app using Xamarin, and my Back End is an ASP.NET Web API. I have a large dataset of cars where I can find the price of the car by Make, Name, Year, Odometer and Engine Capacity. I have tried to average most of the values so I can find data, but many times it just doesn't return anything. So I decided to try and query the database multiple times, but each time it doesn't return anything, I either turn a value into an interval (eg. odometer = 100000 and then odometer >= 80000 && odometer <= 120000). It kinda works like this, but I don't think it's the right way to write it. I was thinking about Strategy Pattern, but can't figure out how to apply in my case.

What I have tried is to make Repository where I get the car object, and then I have six methods that just query the database, each gradually with fewer parameters. There are a lot of If Elses.

public GetCarPriceResponse GetPrice(GetCarPriceRequest car)
        {
            var price = new GetCarPriceResponse
            {
                Errors = new List<string>()
            };

            if (GetPriceFirst(car) == null)
                if (GetPriceSecond(car) == null)
                    if (GetPriceThird(car) == null)
                        if (GetPriceFourth(car) == null)
                            if (GetPriceFifth(car) == null)
                                if (GetPriceSixth(car) == null)
                                {
                                    price.Success = false;
                                    price.Errors.Add("Could not find car
price");
                                }
                                else
                                {
                                    price = GetPriceSixth(car);
                                }
                            else price = GetPriceFifth(car);
                        else price = GetPriceFourth(car);
                    else price = GetPriceThird(car);
                else price = GetPriceSecond(car);
            else price = GetPriceFirst(car);

            price.Success = true;

            return price;
        }

The first function looks like this:

public GetCarPriceResponse GetPriceFirst(GetCarPriceRequest car)
        {
            var prices = _context.CarPrices.Where(p =>
                p.make == car.make &&
                p.model == car.model &&
                p.year == car.year &&
                p.CC == car.CC &&
                p.odometer == car.odometer).ToList();

            if (prices.Count == 0) return null;
            return CalculateAveragePrice(prices);
        }

And the third one like this:

public GetCarPriceResponse GetPriceThird(GetCarPriceRequest car)
        {
            var differenceDown = 0;
            var differenceUp = 0;

            if (car.odometer < 50000)
            {
                differenceDown = 0;
                differenceUp = 50000;
            }
            else if (car.odometer > 50000)
            {
                differenceDown = 50000;
                differenceUp = 50000;
            }
            else if (car.odometer > 215000)
            {
                differenceDown = 50000;
                differenceUp = 0;
            }

            var prices = _context.CarPrices.Where(p =>
                p.make == car.make &&
                p.model == car.model &&
                p.year == car.year &&
                p.CC == car.CC &&
                p.odometer >= car.odometer - differenceDown &&
                p.odometer <= car.odometer + differenceUp).ToList();

            if (prices.Count == 0) return null;
            return CalculateAveragePrice(prices);
        }

In the fourth one I completely eliminate the odometer parameter, and in the sixth one I query a different database that has an average price based on odometer, engine capacity and model year.
This is the fifth method:

 public GetCarPriceResponse GetPriceFifth(GetCarPriceRequest car)
        {
            var prices = _context.CarPrices.Where(p =>
                p.make == car.make &&
                p.model == car.model &&
                p.year >= car.year - 2 &&
                p.year <= car.year + 2 &&
                p.CC == car.CC).ToList();

            if (prices.Count == 0) return null;
            return CalculateAveragePrice(prices);
        }

It works fine for now, but for example if you add an electric car, with the engine capacity of 0, it does not function properly and such.
But I am asking if there is a way to make this code better.

Thank you.


来源: stackexchange

问:
How to make iPhone to communicate to server by using socket?
I know how to make a Java socket in server.
But how to make a socket in iPhone to communicate to server by using socket?</p>

答:
Core Foundation has CFSocket and CFStream. However, there is a library to make using them much nicer.

http://code.google.com/p/cocoaasyncsocket/

I recommend checking that out (as well as reading the docs on the Core Foundation stuff to understand it better).

ContentLicense: CC BY-SA 3.0


问:
Scrape google search results titles and urls using Python
I'm working on a project using Python(3.7) in which I need to scrape the first few Google results for Titles and Urls, I have tried it using BeautifulSoup but it doesn't work:

Here's what I have tried:

```<code>import requests
from my_fake_useragent import UserAgent
from bs4 import BeautifulSoup

ua = UserAgent()

google_url = "https://www.google.com/search?q=python" + "&num=" + str(5)
response = requests.get(google_url, {"User-Agent": ua.random})
soup = BeautifulSoup(response.text, "html.parser")

result_div = soup.find_all('div', attrs={'class': 'g'})

links = []
titles = []
descriptions = []
for r in result_div:
    # Checks if each element is present, else, raise exception
    try:
        link = r.find('a', href=True)
        title = r.find('h3', attrs={'class': 'r'}).get_text()
        description = r.find('span', attrs={'class': 'st'}).get_text()

        # Check to make sure everything is present before appending
        if link != '' and title != '' and description != '':
            links.append(link['href'])
            titles.append(title)
            descriptions.append(description)
    # Next loop if one element is not present
    except:
        continue

print(titles)
</code>```

But it doesn't return anything.

When I try to fetch the HTML like this:

```<code>url = 'https://google.com/search?q=python'
response = requests.get(url)
soup = BeautifulSoup(response.content, 'lxml')
print(soup.prettify())
</code>```

here's what it return: (Added a sample returned HTML code)

```<code><div id="main">
   <div class="ZINbbc xpd O9g5cc uUPGi">
    <div>
     <div class="jfp3ef">
      <a href="/url?q=https://www.python.org/&sa=U&ved=2ahUKEwiCrK7AvsXiAhWxq1kKHTknCuoQFjAAegQIBxAB&usg=AOvVaw0nCy-teBd7nOrThY5YGQ4o">
       <div class="BNeawe vvjwJb AP7Wnd">
        Python.org
       </div>
       <div class="BNeawe UPmit AP7Wnd">
        https://www.python.org
       </div>
      </a>
     </div>
     <div class="NJM3tb">
     </div>
     <div class="jfp3ef">
      <div>
       <div class="BNeawe s3v9rd AP7Wnd">
        <div>
         <div>
          <div class="Ap5OSd">
           <div class="BNeawe s3v9rd AP7Wnd">
            The official home of the Python Programming Language.
           </div>
          </div>
          <div class="v9i61e">
           <div class="BNeawe s3v9rd AP7Wnd">
            <span class="BNeawe">
             <a href="/url?q=https://www.python.org/downloads/&sa=U&ved=2ahUKEwiCrK7AvsXiAhWxq1kKHTknCuoQjBAwAXoECAcQAw&usg=AOvVaw0TKe6ApGOQcWuHcXIkvAT0">
              <span class="XLloXe AP7Wnd">
               Download Python
              </span>
             </a>
            </span>
           </div>
          </div>
          <div class="v9i61e">
           <div class="BNeawe s3v9rd AP7Wnd">
            <span class="BNeawe">
             <a href="/url?q=https://www.python.org/about/gettingstarted/&sa=U&ved=2ahUKEwiCrK7AvsXiAhWxq1kKHTknCuoQjBAwAnoECAcQBQ&usg=AOvVaw03o9Qt-KFSbwECm8-wmUZS">
              <span class="XLloXe AP7Wnd">
               Python For Beginners
              </span>
             </a>
            </span>
           </div>
          </div>
          <div class="v9i61e">
           <div class="BNeawe s3v9rd AP7Wnd">
            <span class="BNeawe">
             <a href="/url?q=https://www.python.org/doc/&sa=U&ved=2ahUKEwiCrK7AvsXiAhWxq1kKHTknCuoQjBAwA3oECAcQBw&usg=AOvVaw3Yz3mO8HXGJoaf35qhyb3V">
              <span class="XLloXe AP7Wnd">
               Documentation
              </span>
             </a>
            </span>
           </div>
          </div>
          <div class="v9i61e">
           <div class="BNeawe s3v9rd AP7Wnd">
            <span class="BNeawe">
             <a href="/url?q=https://docs.python.org/&sa=U&ved=2ahUKEwiCrK7AvsXiAhWxq1kKHTknCuoQjBAwBHoECAcQCQ&usg=AOvVaw0nY6NyZm0wErJJ1RIgTiPm">
              <span class="XLloXe AP7Wnd">
               Python Docs
              </span>
             </a>
            </span>
           </div>
          </div>
          <div class="v9i61e">
           <div class="BNeawe s3v9rd AP7Wnd">
            <span class="BNeawe">
             <a href="/url?q=https://www.python.org/psf/&sa=U&ved=2ahUKEwiCrK7AvsXiAhWxq1kKHTknCuoQjBAwBXoECAcQCw&usg=AOvVaw3HoEDHmdRBcufXuwakPCAz">
              <span class="XLloXe AP7Wnd">
               Python Software Foundation
              </span>
             </a>
            </span>
           </div>
          </div>
          <div>
           <div class="BNeawe s3v9rd AP7Wnd">
            <span class="BNeawe">
             <a href="/url?q=https://www.python.org/downloads/release/python-373/&sa=U&ved=2ahUKEwiCrK7AvsXiAhWxq1kKHTknCuoQjBAwBnoECAcQDQ&usg=AOvVaw3HsJpvpsCvYikd_mP7ndN3">
              <span class="XLloXe AP7Wnd">
               Python 3.7.3
              </span>
             </a>
            </span>
           </div>
          </div>
         </div>
        </div>
       </div>
      </div>
     </div>
    </div>
   </div>
</div>
</code>```

答:
You should try automation selenium library. it allows you to scrape dynamic rendering request(js or ajax) page data.

```<code>from selenium import webdriver
from bs4 import BeautifulSoup
import time
from bs4.element import Tag

driver = webdriver.Chrome('/usr/bin/chromedriver')
google_url = "https://www.google.com/search?q=python" + "&num=" + str(5)
driver.get(google_url)
time.sleep(3)

soup = BeautifulSoup(driver.page_source,'lxml')
result_div = soup.find_all('div', attrs={'class': 'g'})

links = []
titles = []
descriptions = []
for r in result_div:
    # Checks if each element is present, else, raise exception
    try:
        link = r.find('a', href=True)
        title = None
        title = r.find('h3')

        if isinstance(title,Tag):
            title = title.get_text()

        description = None
        description = r.find('span', attrs={'class': 'st'})

        if isinstance(description, Tag):
            description = description.get_text()

        # Check to make sure everything is present before appending
        if link != '' and title != '' and description != '':
            links.append(link['href'])
            titles.append(title)
            descriptions.append(description)
    # Next loop if one element is not present
    except Exception as e:
        print(e)
        continue

print(titles)
print(links)
print(descriptions)
</code>```

O/P:

```<code>['Welcome to Python.org', 'Download Python | Python.org', 'Python Tutorial - W3Schools', 'Introduction to Python - W3Schools', 'Python Programming Language - GeeksforGeeks', 'Python: 7 Important Reasons Why You Should Use Python - Medium', 'Python: 7 Important Reasons Why You Should Use Python - Medium', 'Python Tutorial - Tutorialspoint', 'Python Download and Installation Instructions', 'Python vs C++ - Find Out The 9 Important Differences - eduCBA', None, 'Description']
['https://www.python.org/', 'https://www.python.org/downloads/', 'https://www.w3schools.com/python/', 'https://www.w3schools.com/python/python_intro.asp', 'https://www.geeksforgeeks.org/python-programming-language/', 'https://medium.com/@mindfiresolutions.usa/python-7-important-reasons-why-you-should-use-python-5801a98a0d0b', 'https://medium.com/@mindfiresolutions.usa/python-7-important-reasons-why-you-should-use-python-5801a98a0d0b', 'https://www.tutorialspoint.com/python/', 'https://www.ics.uci.edu/~pattis/common/handouts/pythoneclipsejava/python.html', 'https://www.educba.com/python-vs-c-plus-plus/', '/search?num=5&q=Python&stick=H4sIAAAAAAAAAONgFuLQz9U3MK0yjFeCs7SEs5Ot9JPzc3Pz86yKM1NSyxMri1cxsqVZOQZ4Fi9iZQuoLMnIzwMAlVPV1j0AAAA&sa=X&ved=2ahUKEwigvcqKx8XiAhUOSX0KHdtmBgoQzTooADAQegQIChAC', 'mailto:?body=Python%20https%3A%2F%2Fwww.google.com%2Fsearch%3Fkgmid%3D%2Fm%2F05z1_%26hl%3Den-IN%26kgs%3De1764a9f31831e11%26q%3DPython%26shndl%3D0%26source%3Dsh%2Fx%2Fkp%26entrypoint%3Dsh%2Fx%2Fkp']
['The official home of the Python Programming Language.', 'Looking for Python 2.7? See below for specific releases. Contribute to the PSF by Purchasing a PyCharm License. All proceeds benefit the PSF. Donate Now\xa0...', 'Python can be used on a server to create web applications. ... Our "Show Python" tool makes it easy to learn Python, it shows both the code and the result.', 'What is Python? Python is a popular programming language. It was created by Guido van Rossum, and released in 1991. It is used for: web development\xa0...', 'Python is a widely used general-purpose, high level programming language. It was initially designed by Guido van Rossum in 1991 and developed by Python\xa0...', None, None, None, None, None, None, None]
</code>```

where '/usr/bin/chromedriver' selenium web driver path.

Download selenium web driver for chrome browser:

http://chromedriver.chromium.org/downloads

Install web driver for chrome browser:

https://christopher.su/2015/selenium-chromedriver-ubuntu/

Selenium tutorial:

https://selenium-python.readthedocs.io/

ContentLicense: CC BY-SA 4.0

Body:
I'm working on a project using Python(3.7) in which I need to scrape the first few Google results for Titles and Urls, I have tried it using BeautifulSoup but it doesn't work:

Here's what I have tried:

import requests
from my_fake_useragent import UserAgent
from bs4 import BeautifulSoup

ua = UserAgent()

google_url = "https://www.google.com/search?q=python" + "&num=" + str(5)
response = requests.get(google_url, {"User-Agent": ua.random})
soup = BeautifulSoup(response.text, "html.parser")

result_div = soup.find_all('div', attrs={'class': 'g'})

links = []
titles = []
descriptions = []
for r in result_div:
    # Checks if each element is present, else, raise exception
    try:
        link = r.find('a', href=True)
        title = r.find('h3', attrs={'class': 'r'}).get_text()
        description = r.find('span', attrs={'class': 'st'}).get_text()

        # Check to make sure everything is present before appending
        if link != '' and title != '' and description != '':
            links.append(link['href'])
            titles.append(title)
            descriptions.append(description)
    # Next loop if one element is not present
    except:
        continue

print(titles)

But it doesn't return anything.

When I try to fetch the HTML like this:

url = 'https://google.com/search?q=python'
response = requests.get(url)
soup = BeautifulSoup(response.content, 'lxml')
print(soup.prettify())

here's what it return: (Added a sample returned HTML code)

        Python.org

        https://www.python.org

            The official home of the Python Programming Language.

               Download Python

               Python For Beginners

               Documentation

               Python Docs

               Python Software Foundation

               Python 3.7.3

Body:
You should try automation selenium library. it allows you to scrape dynamic rendering request(js or ajax) page data.

from selenium import webdriver
from bs4 import BeautifulSoup
import time
from bs4.element import Tag

driver = webdriver.Chrome('/usr/bin/chromedriver')
google_url = "https://www.google.com/search?q=python" + "&num=" + str(5)
driver.get(google_url)
time.sleep(3)

soup = BeautifulSoup(driver.page_source,'lxml')
result_div = soup.find_all('div', attrs={'class': 'g'})

links = []
titles = []
descriptions = []
for r in result_div:
    # Checks if each element is present, else, raise exception
    try:
        link = r.find('a', href=True)
        title = None
        title = r.find('h3')

        if isinstance(title,Tag):
            title = title.get_text()

        description = None
        description = r.find('span', attrs={'class': 'st'})

        if isinstance(description, Tag):
            description = description.get_text()

        # Check to make sure everything is present before appending
        if link != '' and title != '' and description != '':
            links.append(link['href'])
            titles.append(title)
            descriptions.append(description)
    # Next loop if one element is not present
    except Exception as e:
        print(e)
        continue

print(titles)
print(links)
print(descriptions)

O/P:

['Welcome to Python.org', 'Download Python | Python.org', 'Python Tutorial - W3Schools', 'Introduction to Python - W3Schools', 'Python Programming Language - GeeksforGeeks', 'Python: 7 Important Reasons Why You Should Use Python - Medium', 'Python: 7 Important Reasons Why You Should Use Python - Medium', 'Python Tutorial - Tutorialspoint', 'Python Download and Installation Instructions', 'Python vs C++ - Find Out The 9 Important Differences - eduCBA', None, 'Description']
['https://www.python.org/', 'https://www.python.org/downloads/', 'https://www.w3schools.com/python/', 'https://www.w3schools.com/python/python_intro.asp', 'https://www.geeksforgeeks.org/python-programming-language/', 'https://medium.com/@mindfiresolutions.usa/python-7-important-reasons-why-you-should-use-python-5801a98a0d0b', 'https://medium.com/@mindfiresolutions.usa/python-7-important-reasons-why-you-should-use-python-5801a98a0d0b', 'https://www.tutorialspoint.com/python/', 'https://www.ics.uci.edu/~pattis/common/handouts/pythoneclipsejava/python.html', 'https://www.educba.com/python-vs-c-plus-plus/', '/search?num=5&q=Python&stick=H4sIAAAAAAAAAONgFuLQz9U3MK0yjFeCs7SEs5Ot9JPzc3Pz86yKM1NSyxMri1cxsqVZOQZ4Fi9iZQuoLMnIzwMAlVPV1j0AAAA&sa=X&ved=2ahUKEwigvcqKx8XiAhUOSX0KHdtmBgoQzTooADAQegQIChAC', 'mailto:?body=Python%20https%3A%2F%2Fwww.google.com%2Fsearch%3Fkgmid%3D%2Fm%2F05z1_%26hl%3Den-IN%26kgs%3De1764a9f31831e11%26q%3DPython%26shndl%3D0%26source%3Dsh%2Fx%2Fkp%26entrypoint%3Dsh%2Fx%2Fkp']
['The official home of the Python Programming Language.', 'Looking for Python 2.7? See below for specific releases. Contribute to the PSF by Purchasing a PyCharm License. All proceeds benefit the PSF. Donate Now\xa0...', 'Python can be used on a server to create web applications. ... Our "Show Python" tool makes it easy to learn Python, it shows both the code and the result.', 'What is Python? Python is a popular programming language. It was created by Guido van Rossum, and released in 1991. It is used for: web development\xa0...', 'Python is a widely used general-purpose, high level programming language. It was initially designed by Guido van Rossum in 1991 and developed by Python\xa0...', None, None, None, None, None, None, None]

where '/usr/bin/chromedriver' selenium web driver path.

Download selenium web driver for chrome browser:

http://chromedriver.chromium.org/downloads

Install web driver for chrome browser:

https://christopher.su/2015/selenium-chromedriver-ubuntu/

Selenium tutorial:

https://selenium-python.readthedocs.io/


问:
Git 'pre-receive' hook and 'git-clang-format' script to reliably reject pushes that violate code style conventions
Let's immediately start with a scrap of the pre-receive hook that I've already written:

```<code>#!/bin/sh
##
  format_bold='\033[1m'
   format_red='\033[31m'
format_yellow='\033[33m'
format_normal='\033[0m'
##
  format_error="${format_bold}${format_red}%s${format_normal}"
format_warning="${format_bold}${format_yellow}%s${format_normal}"
##
stdout() {
  format="${1}"
  shift
  printf "${format}" "${@}"
}
##
stderr() {
  stdout "${@}" 1>&2
}
##
output() {
  format="${1}"
  shift
  stdout "${format}\n" "${@}"
}
##
error() {
  format="${1}"
  shift
  stderr "${format_error}: ${format}\n" 'error' "${@}"
}
##
warning() {
  format="${1}"
  shift
  stdout "${format_warning}: ${format}\n" 'warning' "${@}"
}
##
die() {
  error "${@}"
  exit 1
}
##
git() {
  command git --no-pager "${@}"
}
##
list() {
  git rev-list "${@}"
}
##
clang_format() {
  git clang-format --style='file' "${@}"
}
##
while read sha1_old sha1_new ref; do
  case "${ref}" in
  refs/heads/*)
    branch="$(expr "${ref}" : 'refs/heads/\(.*\)')"
    if [ "$(expr "${sha1_new}" : '0*$')" -ne 0 ]; then # delete
      unset sha1_new
      # ...
    else # update
      if [ "$(expr "${sha1_old}" : '0*$')" -ne 0 ]; then # create
        unset sha1_old
        sha1_range="${sha1_new}"
      else
        sha1_range="${sha1_old}..${sha1_new}"
        # ...
        fi
      fi
      # ...
             GIT_WORK_TREE="$(mktemp --tmpdir -d 'gitXXXXXX')"
      export GIT_WORK_TREE
             GIT_DIR="${GIT_WORK_TREE}/.git"
      export GIT_DIR
      mkdir -p "${GIT_DIR}"
      cp -a * "${GIT_DIR}/"
      ln -s "${PWD}/../.clang-format" "${GIT_WORK_TREE}/"
      error=
      for sha1 in $(list "${sha1_range}"); do
        git checkout --force "${sha1}" > '/dev/null' 2>&1
        if [ "$(list --count "${sha1}")" -eq 1 ]; then
          # What should I put here?
        else
          git reset --soft 'HEAD~1' > '/dev/null' 2>&1
        fi
        diff="$(clang_format --diff)"
        if [ "${diff%% *}" = 'diff' ]; then
          error=1
          error '%s: %s\n%s'                                                   \
                'Code style issues detected'                                   \
                "${sha1}"                                                      \
                "${diff}"                                                      \
                1>&2
        fi
      done
      if [ -n "${error}" ]; then
        die '%s' 'Code style issues detected'
      fi
    fi
    ;;
  refs/tags/*)
    tag="$(expr "${ref}" : 'refs/tags/\(.*\)')"
    # ...
    ;;
  *)
    # ...
    ;;
  esac
done
exit 0
</code>```

NOTE:

Places with irrelevant code are stubbed with # ....

NOTE:

If you are not familiar with git-clang-format, take a look here.

That hook works as expected, and so far, I didn't notice any bugs, but if you spot any problem or have an improvement suggestion, I'd appreciate any report.  Probably, I should give a comment on what's the intention behind this hook.  Well, it does check every pushed revision for compliance with code style conventions using git-clang-format, and if any of them does not comply, it will output the relevant diff (the one telling developers what should be fixed) for each of them.  Basically, I have two in-depth questions regarding this hook.

First, notice that I perform copy of the remote's (server) bare repository to some temporary directory and check out the code for analysis there.  Let me explain the intention of this.  Note that I do several git checkouts and git resets (due to for loop) in order to analyze all of the pushed revisions individually with git-clang-format.  What I am trying to avoid here, is the (possible) concurrency issue on push access to the remote's (server) bare repository.  That is, I'm under impression that if multiple developers will try to push at the same time to a remote with this pre-receive hook installed, that might cause problems if each of these push "sessions" does not do git checkouts and git resets with its private copy of the repository.  So, to put it simple, does git-daemon have built-in lock management for concurrent push "sessions"?  Will it execute the corresponding pre-receive hook instances strictly sequentially or there is a possibility of interleaving (which can potentially cause undefined behavior)?  Something tells me that there should be a built-in solution for this problem with concrete guarantees, otherwise how would remotes work in general (even without complex hooks) being subjected to concurrent pushes?  If there is such a built-in solution, then the copy is redundant and simply reusing the bare repository would actually speed up the processing.  By the way, any reference to official documentation regarding this question is very welcome.

Second, git-clang-format processes only staged (but not committed) changes vs. specific commit (HEAD by default).  Thus, you can easily see where a corner case lies.  Yes, it's with the root commits (revisions).  In fact, git reset --soft 'HEAD~1' cannot be applied to root commits as they have no parents to reset to.  Hence, the following check with my second question is there:

```<code>        if [ "$(list --count "${sha1}")" -eq 1 ]; then
          # What should I put here?
        else
          git reset --soft 'HEAD~1' > '/dev/null' 2>&1
        fi
</code>```

I've tried git update-ref -d 'HEAD' but this breaks the repository in such a way that git-clang-format is not able to process it anymore.  I believe this is related to the fact that all of these pushed revisions that are being analyzed (including this root one) do not really belong to any branch yet.  That is, they are in detached HEAD state.  It would be perfect to find a solution to this corner case as well, so that initial commits can also undergo the same check by git-clang-format for compliance with code style conventions.

Peace.

答:
Condensed

I had a little bit of trouble understanding the first example, in part due to the length and extra tidbits that make it useful for the OP's specific use case. I combed through and condensed it down to this:

```<code>ref_name=$1
new_rev=$3

# only check branches, not tags or bare commits
if [ -z $(echo $ref_name | grep "refs/heads/") ]; then
  exit 0
fi

# don't check empty branches
if [ "$(expr "${new_rev}" : '0*$')" -ne 0 ]; then
  exit 0
fi

# Checkout a copy of the branch (but also changes HEAD)
my_work_tree=$(mktemp -d -t git-work-tree.XXXXXXXX) 2>/dev/null
git --work-tree="${my_work_tree}" --git-dir="." checkout $new_rev -f >/dev/null

# Do the formatter check
echo "Checking code formatting..."
pushd ${my_work_tree} >/dev/null
prettier './**/*.{js,css,html,json,md}' --list-different
my_status=$?
popd >/dev/null

# reset HEAD to master, and cleanup
git --work-tree="${my_work_tree}" --git-dir="." checkout master -f >/dev/null
rm -rf "${my_work_tree}"

# handle error, if any
if [ "0" != "$my_status" ]; then
  echo "Please format the files listed above and re-commit."
  echo "(and don't forget your .prettierrc, if you have one)"
  exit 1
fi
</code>```

This example is using Prettier, but it'll map pretty well to clang-format, eslint, etc. There are a few limitations to the (perhaps oversimplified, but working) example above. I'd recommend diving deeper...

Better, but longer

Once you've grok'd that I'd also recommend taking a scroll down towards the bottom of this one:

Reject Ugly Commits with Server-Side Git Hooks

Body:
Let's immediately start with a scrap of the pre-receive hook that I've already written:

#!/bin/sh
##
  format_bold='\033[1m'
   format_red='\033[31m'
format_yellow='\033[33m'
format_normal='\033[0m'
##
  format_error="${format_bold}${format_red}%s${format_normal}"
format_warning="${format_bold}${format_yellow}%s${format_normal}"
##
stdout() {
  format="${1}"
  shift
  printf "${format}" "${@}"
}
##
stderr() {
  stdout "${@}" 1>&2
}
##
output() {
  format="${1}"
  shift
  stdout "${format}\n" "${@}"
}
##
error() {
  format="${1}"
  shift
  stderr "${format_error}: ${format}\n" 'error' "${@}"
}
##
warning() {
  format="${1}"
  shift
  stdout "${format_warning}: ${format}\n" 'warning' "${@}"
}
##
die() {
  error "${@}"
  exit 1
}
##
git() {
  command git --no-pager "${@}"
}
##
list() {
  git rev-list "${@}"
}
##
clang_format() {
  git clang-format --style='file' "${@}"
}
##
while read sha1_old sha1_new ref; do
  case "${ref}" in
  refs/heads/*)
    branch="$(expr "${ref}" : 'refs/heads/\(.*\)')"
    if [ "$(expr "${sha1_new}" : '0*$')" -ne 0 ]; then # delete
      unset sha1_new
      # ...
    else # update
      if [ "$(expr "${sha1_old}" : '0*$')" -ne 0 ]; then # create
        unset sha1_old
        sha1_range="${sha1_new}"
      else
        sha1_range="${sha1_old}..${sha1_new}"
        # ...
        fi
      fi
      # ...
             GIT_WORK_TREE="$(mktemp --tmpdir -d 'gitXXXXXX')"
      export GIT_WORK_TREE
             GIT_DIR="${GIT_WORK_TREE}/.git"
      export GIT_DIR
      mkdir -p "${GIT_DIR}"
      cp -a * "${GIT_DIR}/"
      ln -s "${PWD}/../.clang-format" "${GIT_WORK_TREE}/"
      error=
      for sha1 in $(list "${sha1_range}"); do
        git checkout --force "${sha1}" > '/dev/null' 2>&1
        if [ "$(list --count "${sha1}")" -eq 1 ]; then
          # What should I put here?
        else
          git reset --soft 'HEAD~1' > '/dev/null' 2>&1
        fi
        diff="$(clang_format --diff)"
        if [ "${diff%% *}" = 'diff' ]; then
          error=1
          error '%s: %s\n%s'                                                   \
                'Code style issues detected'                                   \
                "${sha1}"                                                      \
                "${diff}"                                                      \
                1>&2
        fi
      done
      if [ -n "${error}" ]; then
        die '%s' 'Code style issues detected'
      fi
    fi
    ;;
  refs/tags/*)
    tag="$(expr "${ref}" : 'refs/tags/\(.*\)')"
    # ...
    ;;
  *)
    # ...
    ;;
  esac
done
exit 0

NOTE:

Places with irrelevant code are stubbed with # ....

NOTE:

If you are not familiar with git-clang-format, take a look here.

That hook works as expected, and so far, I didn't notice any bugs, but if you spot any problem or have an improvement suggestion, I'd appreciate any report.  Probably, I should give a comment on what's the intention behind this hook.  Well, it does check every pushed revision for compliance with code style conventions using git-clang-format, and if any of them does not comply, it will output the relevant diff (the one telling developers what should be fixed) for each of them.  Basically, I have two in-depth questions regarding this hook.

First, notice that I perform copy of the remote's (server) bare repository to some temporary directory and check out the code for analysis there.  Let me explain the intention of this.  Note that I do several git checkouts and git resets (due to for loop) in order to analyze all of the pushed revisions individually with git-clang-format.  What I am trying to avoid here, is the (possible) concurrency issue on push access to the remote's (server) bare repository.  That is, I'm under impression that if multiple developers will try to push at the same time to a remote with this pre-receive hook installed, that might cause problems if each of these push "sessions" does not do git checkouts and git resets with its private copy of the repository.  So, to put it simple, does git-daemon have built-in lock management for concurrent push "sessions"?  Will it execute the corresponding pre-receive hook instances strictly sequentially or there is a possibility of interleaving (which can potentially cause undefined behavior)?  Something tells me that there should be a built-in solution for this problem with concrete guarantees, otherwise how would remotes work in general (even without complex hooks) being subjected to concurrent pushes?  If there is such a built-in solution, then the copy is redundant and simply reusing the bare repository would actually speed up the processing.  By the way, any reference to official documentation regarding this question is very welcome.

Second, git-clang-format processes only staged (but not committed) changes vs. specific commit (HEAD by default).  Thus, you can easily see where a corner case lies.  Yes, it's with the root commits (revisions).  In fact, git reset --soft 'HEAD~1' cannot be applied to root commits as they have no parents to reset to.  Hence, the following check with my second question is there:

        if [ "$(list --count "${sha1}")" -eq 1 ]; then
          # What should I put here?
        else
          git reset --soft 'HEAD~1' > '/dev/null' 2>&1
        fi

I've tried git update-ref -d 'HEAD' but this breaks the repository in such a way that git-clang-format is not able to process it anymore.  I believe this is related to the fact that all of these pushed revisions that are being analyzed (including this root one) do not really belong to any branch yet.  That is, they are in detached HEAD state.  It would be perfect to find a solution to this corner case as well, so that initial commits can also undergo the same check by git-clang-format for compliance with code style conventions.

Peace.

Body:
Condensed

I had a little bit of trouble understanding the first example, in part due to the length and extra tidbits that make it useful for the OP's specific use case. I combed through and condensed it down to this:

ref_name=$1
new_rev=$3

# only check branches, not tags or bare commits
if [ -z $(echo $ref_name | grep "refs/heads/") ]; then
  exit 0
fi

# don't check empty branches
if [ "$(expr "${new_rev}" : '0*$')" -ne 0 ]; then
  exit 0
fi

# Checkout a copy of the branch (but also changes HEAD)
my_work_tree=$(mktemp -d -t git-work-tree.XXXXXXXX) 2>/dev/null
git --work-tree="${my_work_tree}" --git-dir="." checkout $new_rev -f >/dev/null

# Do the formatter check
echo "Checking code formatting..."
pushd ${my_work_tree} >/dev/null
prettier './**/*.{js,css,html,json,md}' --list-different
my_status=$?
popd >/dev/null

# reset HEAD to master, and cleanup
git --work-tree="${my_work_tree}" --git-dir="." checkout master -f >/dev/null
rm -rf "${my_work_tree}"

# handle error, if any
if [ "0" != "$my_status" ]; then
  echo "Please format the files listed above and re-commit."
  echo "(and don't forget your .prettierrc, if you have one)"
  exit 1
fi

This example is using Prettier, but it'll map pretty well to clang-format, eslint, etc. There are a few limitations to the (perhaps oversimplified, but working) example above. I'd recommend diving deeper...

Better, but longer

Once you've grok'd that I'd also recommend taking a scroll down towards the bottom of this one:

Reject Ugly Commits with Server-Side Git Hooks


问:
meteo.js:21 Uncaught SyntaxError: await is only valid in async function
I have a problem in my code I do not see the weather API appear in my code

Uncaught SyntaxError: await is only valid in async function meteo.js:21

if (WithIP) {
  const ip = await fetch('https://api.ipify.org/?format=json%27')
    .then(resultat => resultat.json())
    .then(json => json.ip);

  ville = await fetch("http://api.ipstack.com/json/' + ip + '?access_key=' + access_key")
    .then(resultat => resultat.json())
    .then(json => json.city);

} else {
  ville = document.querySelector('#ville').textContent;
}

{
  const meteo = await fetch('http://api.openweathermap.org/data/2.5/weather?q=Marseille&appid=33119b4a3fa1ad278805578d27ea15de&lang=fr&units=metric%27')
    .then(resultat => resultat.json())
    .then(json => json)
```

答:
Here is a quote from Mozilla Developers :

An async function can contain an await expression that pauses the execution of the async function and waits for the passed Promise's resolution, and then resumes the async function's execution and returns the resolved value.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function


问:
How to add a comment to a page using ajax
I am trying to allow the user to make a comment in an article but somehow, so that my page is not reloaded, I have to use ajax and I don't have much knowledge about it. This is how my comment section looks like:

```<code><div class="usrcmmnt_list">
      @foreach($comments as $comment)
      <div class="usrcmmnt flex_box">
        <div class="usrcmmnt_pic">
          <img src="{{ $comment->user['profile_image'] }}">
        </div>
        <div class="usrcmmnt_area">
          <p class="usrcmmnt_name">{{ $comment->user['name'] }}</p>
          <div class="usrcmmnt_box">
            <p class="usrcmmnt_text">{{$comment['content']}}</p>
            <p class="usrcmmnt_time"><img src="{{ url('/img/icon_time.png') }}">{{ date("m/d H:m", strtotime($comment->created_at)) }}</p>
          </div>
        </div>
      </div>
      @endforeach
    </div>
    <div class="comment_write">
      <textarea placeholder="Write a comment" name="comment" id="comment" maxLength="255"></textarea>
      <p class="usrcmmnt_text" id="textarea_warning"></p>
      <span class="alert"></span>
      <button class="btn btn_orange btn_m_2" id="saveComment" type="submit">Post comment</button>
    </div>
</div>
</code>```

In my script part, I have this one but it only copies the existing comments. This is just for my testing:

```<code>$('.comment_write button').on('click', function(e){
  e.preventDefault();
  var tmp = document.createElement('div');
  $(tmp).load('myurl', function(data){
    // usrcmmnt_list
    var tmp2 = document.createElement('div');
    $(tmp2).html(data);
    var list = $(tmp2).find('.usrcmmnt_list');

    $(".usrcmmnt_list").append(list);
  });
});
</code>```

How can I attain my goal using ajax?

答:
There are multiple approaches for this, one of them:

you could move your comments loop (@foreach) into a partial

create an endpoint to save the user comment and return the new comments partial as html

update the DOM

1. Create a new partial \resources\views\partials\comments.blade.php and include it into your comments section:

```<code>   @if ($comments)
    @foreach($comments as $comment)
          <div class="usrcmmnt flex_box">
            <div class="usrcmmnt_pic">
              <img src="{{ $comment->user['profile_image'] }}">
            </div>
            <div class="usrcmmnt_area">
              <p class="usrcmmnt_name">{{ $comment->user['name'] }}</p>
              <div class="usrcmmnt_box">
                <p class="usrcmmnt_text">{{$comment['content']}}</p>
                <p class="usrcmmnt_time"><img src="{{ url('/img/icon_time.png') }}">{{ date("m/d H:m", strtotime($comment->created_at)) }}</p>
              </div>
            </div>
          </div>
          @endforeach
    @else
    No comments
    @endif
</code>```

2. Your comments section should look like this:

```<code><div class="usrcmmnt_list">
    <div id="comments-list">
    @include('partials.comments')
    </div>
    <div class="comment_write">
      <form method="post" action="{{ route('save.comment') }}" id="saveCommentForm">
      <textarea placeholder="Write a comment" name="comment" id="comment" maxLength="255"></textarea>
      <p class="usrcmmnt_text" id="textarea_warning"></p>
      <span class="alert"></span>
      <button class="btn btn_orange btn_m_2" id="saveComment" type="submit">Post comment</button>
      </form>
    </div>
</div>
</code>```

3. Create your save comment method in CommentsController (which you will use to save the user comment via your ajax call):

```<code>public function save(Request $request)
{
    /* we assume that your ajax save route is named comment.save */
    /* you might need the postId if you save the comments for a post */
    $comment = $request->input('comment');
    $user    = auth()->user();
    $comment = Comment::create([
        'user_id'=> $user->id,
        'content'=> $comment
    ]);
    $comments = Comment::with('user')->all();
    return view('comments.blade');
}
</code>```

4. Your ajax call:

```<code>$(document).ready(function(){
    $('#saveCommentForm').on('submit', function(event) {
        event.preventDefault(); // prevent the form from submiting
        var $form = $(this),
            url = $form.attr('action');

        $.ajax({
            url: url,
            method: 'POST',
            data: $form.serialize(),
            success: function(response) {
                $('#comments-list').html(response); //update the dom
            },
            error: function() {
                alert('An error occurred. Please try again later.');
            }
        });
    });
});
</code>```

I hope this will help you get started.

Body:
I am trying to allow the user to make a comment in an article but somehow, so that my page is not reloaded, I have to use ajax and I don't have much knowledge about it. This is how my comment section looks like:

      @foreach($comments as $comment)

          user['profile_image'] }}">

{{ $comment->user['name'] }}

{{$comment['content']}}

{{ date("m/d H:m", strtotime($comment->created_at)) }}

      @endforeach

      <textarea placeholder="Write a comment" name="comment" id="comment" maxLength="255"></textarea>

      <button class="btn btn_orange btn_m_2" id="saveComment" type="submit">Post comment</button>

In my script part, I have this one but it only copies the existing comments. This is just for my testing:

$('.comment_write button').on('click', function(e){
  e.preventDefault();
  var tmp = document.createElement('div');
  $(tmp).load('myurl', function(data){
    // usrcmmnt_list
    var tmp2 = document.createElement('div');
    $(tmp2).html(data);
    var list = $(tmp2).find('.usrcmmnt_list');

    $(".usrcmmnt_list").append(list);
  });
});

How can I attain my goal using ajax?

Body:
There are multiple approaches for this, one of them:

you could move your comments loop (@foreach) into a partial

create an endpoint to save the user comment and return the new comments partial as html

update the DOM

1. Create a new partial \resources\views\partials\comments.blade.php and include it into your comments section:

   @if ($comments)
    @foreach($comments as $comment)
          <div class="usrcmmnt flex_box">
            <div class="usrcmmnt_pic">
              <img src="{{ $comment->user['profile_image'] }}">
            </div>
            <div class="usrcmmnt_area">
              <p class="usrcmmnt_name">{{ $comment->user['name'] }}</p>
              <div class="usrcmmnt_box">
                <p class="usrcmmnt_text">{{$comment['content']}}</p>
                <p class="usrcmmnt_time"><img src="{{ url('/img/icon_time.png') }}">{{ date("m/d H:m", strtotime($comment->created_at)) }}</p>
              </div>
            </div>
          </div>
          @endforeach
    @else
    No comments
    @endif

2. Your comments section should look like this:

<div class="usrcmmnt_list">
    <div id="comments-list">
    @include('partials.comments')
    </div>
    <div class="comment_write">
      <form method="post" action="{{ route('save.comment') }}" id="saveCommentForm">
      <textarea placeholder="Write a comment" name="comment" id="comment" maxLength="255"></textarea>
      <p class="usrcmmnt_text" id="textarea_warning"></p>
      <span class="alert"></span>
      <button class="btn btn_orange btn_m_2" id="saveComment" type="submit">Post comment</button>
      </form>
    </div>
</div>

3. Create your save comment method in CommentsController (which you will use to save the user comment via your ajax call):

public function save(Request $request)
{
    /* we assume that your ajax save route is named comment.save */
    /* you might need the postId if you save the comments for a post */
    $comment = $request->input('comment');
    $user    = auth()->user();
    $comment = Comment::create([
        'user_id'=> $user->id,
        'content'=> $comment
    ]);
    $comments = Comment::with('user')->all();
    return view('comments.blade');
}

4. Your ajax call:

$(document).ready(function(){
    $('#saveCommentForm').on('submit', function(event) {
        event.preventDefault(); // prevent the form from submiting
        var $form = $(this),
            url = $form.attr('action');

        $.ajax({
            url: url,
            method: 'POST',
            data: $form.serialize(),
            success: function(response) {
                $('#comments-list').html(response); //update the dom
            },
            error: function() {
                alert('An error occurred. Please try again later.');
            }
        });
    });
});

I hope this will help you get started.


问:
Cannot find FileMerge (opendiff tool) but I have xcode 4.6 installed
When I attempt to run FileMerge as a GUI for Opendiff, I receive an error:

```<code>$ git mergetool -t opendiff
Merging:
Gemfile
Gemfile.lock
...

Normal merge conflict for 'Gemfile':
  {local}: modified file
  {remote}: modified file
Hit return to start merge resolution tool (opendiff):
2013-12-26 20:00:20.248 opendiff[22367:e07] Couldn't find FileMerge
Gemfile seems unchanged.
Was the merge successful? [y/n] ^C
$
</code>```

I have installed XCode 4.6.3 and Command Line Tools for Xcode April 2013.  I am running OSX 10.7.5

I have tried solutions from the following two links with no success:

git diff with opendiff gives "Couldn't launch FileMerge" error

Is filemerge still available after Xcode 4.3 installation?

When I go to Xcode -> Open Developer Tool I do not see FileMerge in the list of options.  There is a More Developer Tools link that takes me here: https://developer.apple.com/downloads/index.action?name=for%20Xcode%20-

How do I get FileMerge working?

答:
if you have xcode installed, then you can probably run the following from the command line to open FileMerge directly </p>

```<code>open /Applications/Xcode.app/Contents/Applications/FileMerge.app/
</code>```

Body:
When I attempt to run FileMerge as a GUI for Opendiff, I receive an error:

$ git mergetool -t opendiff
Merging:
Gemfile
Gemfile.lock
...

Normal merge conflict for 'Gemfile':
  {local}: modified file
  {remote}: modified file
Hit return to start merge resolution tool (opendiff):
2013-12-26 20:00:20.248 opendiff[22367:e07] Couldn't find FileMerge
Gemfile seems unchanged.
Was the merge successful? [y/n] ^C
$

I have installed XCode 4.6.3 and Command Line Tools for Xcode April 2013.  I am running OSX 10.7.5

I have tried solutions from the following two links with no success:

git diff with opendiff gives "Couldn't launch FileMerge" error

Is filemerge still available after Xcode 4.3 installation?

When I go to Xcode -> Open Developer Tool I do not see FileMerge in the list of options.  There is a More Developer Tools link that takes me here: https://developer.apple.com/downloads/index.action?name=for%20Xcode%20-

How do I get FileMerge working?

Body:
if you have xcode installed, then you can probably run the following from the command line to open FileMerge directly

open /Applications/Xcode.app/Contents/Applications/FileMerge.app/


问:
Problem trying to retrieve info from a json file with an api with php
first, thanks in advance for your help.

I have some problems trying to get data from an online JSON file. I using PHP (with cURL). I can access the file and I can put an echo and see all of the "raw" data in it. I want to find a way to show only the type of data I want (for example, only a movie). I use the foreach but I got a notice and a warning.

I tried with the second argument of json_decode and try with foreach but it doesn't work. I did some research but even if I try, there is always the same errors. I tried with "movie" from the beginning of the file but I also have the same error. Is it because "movie" doesn't have a "[" (it is also twice)? Then, I tried with the "apiver" but same error.

//getting the access of the file - cURL is working fine
$sJSON = see_json('link');
$aJSON = json_decode($sJSON, true);

foreach($aJSON->apiver as $mydatas) {
  foreach ($mydatas->values as $value) {
    echo $value->value . "
";
  }
}
```

```//beginning of the JSON file
"movie": {
        "1010414": {
            "title_fr": "Godzilla II - Roi des Monstres",
            "lang_ov": "en",
            "release_de_ch": "2019-05-30",
            "title": "Godzilla: King of the Monsters",
            "release_fr_ch": "2019-05-29",
            "title_de": "Godzilla II: King of the Monsters",
            "id": "1010414"
        },
        "1011095": {
            "title_fr": "Le Parc des merveilles",
            "lang_ov": "en",
            "release_de_ch": "2019-04-11",
            "title": "Wonder Park",
            "release_fr_ch": "2019-04-03",
            "title_de": "Willkommen im Wunder Park",
            "id": "1011095"

//far in the file
"apiver": 210,
    "sched": [
        {
            "ts": 1559201400,
            "id": "VS1258",
            "duration": 129,
            "movie": "1012351",
            "site": "SPE",
            "aud": 3,
            "age": "6/10",
            "lang": "de"
        },
        {
            "ts": 1559202300,
            "id": "VM33930",
            "duration": 85,
            "movie": "1012655",
            "site": "MOS",
            "aud": 3,
            "age": "6/6",
            "lang": "de"
```

I want to show all data from "apiver" but it results in 2 errors :

Notice: Trying to get property 'apiver' of non-object in
  C:\xampp\htdocs\Cinema Pathe\curl.php on line 28

Warning: Invalid argument supplied for foreach() in
  C:\xampp\htdocs\Cinema Pathe\curl.php on line 28

What am I doing wrong?

Again, thanks for your help!

答: Can change to $aJSON['apiver'] in you foreach() loop or change this line $aJSON = json_decode($sJSON, true); to $aJSON = json_decode($sJSON);

Body:
first, thanks in advance for your help.

I have some problems trying to get data from an online JSON file. I using PHP (with cURL). I can access the file and I can put an echo and see all of the "raw" data in it. I want to find a way to show only the type of data I want (for example, only a movie). I use the foreach but I got a notice and a warning.

I tried with the second argument of json_decode and try with foreach but it doesn't work. I did some research but even if I try, there is always the same errors. I tried with "movie" from the beginning of the file but I also have the same error. Is it because "movie" doesn't have a "[" (it is also twice)? Then, I tried with the "apiver" but same error.

//getting the access of the file - cURL is working fine
$sJSON = see_json('link');
$aJSON = json_decode($sJSON, true);

foreach($aJSON->apiver as $mydatas) {
  foreach ($mydatas->values as $value) {
    echo $value->value . "
";
  }
}

//beginning of the JSON file
"movie": {
        "1010414": {
            "title_fr": "Godzilla II - Roi des Monstres",
            "lang_ov": "en",
            "release_de_ch": "2019-05-30",
            "title": "Godzilla: King of the Monsters",
            "release_fr_ch": "2019-05-29",
            "title_de": "Godzilla II: King of the Monsters",
            "id": "1010414"
        },
        "1011095": {
            "title_fr": "Le Parc des merveilles",
            "lang_ov": "en",
            "release_de_ch": "2019-04-11",
            "title": "Wonder Park",
            "release_fr_ch": "2019-04-03",
            "title_de": "Willkommen im Wunder Park",
            "id": "1011095"

//far in the file
"apiver": 210,
    "sched": [
        {
            "ts": 1559201400,
            "id": "VS1258",
            "duration": 129,
            "movie": "1012351",
            "site": "SPE",
            "aud": 3,
            "age": "6/10",
            "lang": "de"
        },
        {
            "ts": 1559202300,
            "id": "VM33930",
            "duration": 85,
            "movie": "1012655",
            "site": "MOS",
            "aud": 3,
            "age": "6/6",
            "lang": "de"

I want to show all data from "apiver" but it results in 2 errors :

Notice: Trying to get property 'apiver' of non-object in
  C:\xampp\htdocs\Cinema Pathe\curl.php on line 28

Warning: Invalid argument supplied for foreach() in
  C:\xampp\htdocs\Cinema Pathe\curl.php on line 28

What am I doing wrong?

Again, thanks for your help!


答:
You can only use await in an async function - to avoid making your whole code an async function, use IIFEs like so:

```<code>const ip = (async () => await fetch('https://api.ipify.org/?format=json%27'))();
</code>```

Because you're still using .then chaining, you could just remove the await part completely and just use .then for continuity.

```<code>fetch('https://api.ipify.org/?format=json%27').then(resultat => resultat.json()).then(...);
</code>```

Title: meteo.js:21 Uncaught SyntaxError: await is only valid in async function

Body:
I have a problem in my code I do not see the weather API appear in my code

Uncaught SyntaxError: await is only valid in async function meteo.js:21

if (WithIP) {
  const ip = await fetch('https://api.ipify.org/?format=json%27')
    .then(resultat => resultat.json())
    .then(json => json.ip);

  ville = await fetch("http://api.ipstack.com/json/' + ip + '?access_key=' + access_key")
    .then(resultat => resultat.json())
    .then(json => json.city);

} else {
  ville = document.querySelector('#ville').textContent;
}

{
  const meteo = await fetch('http://api.openweathermap.org/data/2.5/weather?q=Marseille&appid=33119b4a3fa1ad278805578d27ea15de&lang=fr&units=metric%27')
    .then(resultat => resultat.json())
    .then(json => json)

Body:
You can only use await in an async function - to avoid making your whole code an async function, use IIFEs like so:

const ip = (async () => await fetch('https://api.ipify.org/?format=json%27'))();

Because you're still using .then chaining, you could just remove the await part completely and just use .then for continuity.

fetch('https://api.ipify.org/?format=json%27').then(resultat => resultat.json()).then(...);


问:
How to use * in KEYNAME for ZUNIONSTORE
How can i union 'n' number of sorted sets by using * in Keyname (key-1-1, key-1-,2, key-1-3,..key-1-n) of ZUNIONSTORE command. Is there any other similar option as i have around 55k sortedsets to be joined.</p>

答:
Set operations require explicit key names, not patterns. The only way to do it is the specify each of your 55K keys in the command.

That said, if you're unioning 55K sets, you're probably using it wrong.

Title: How to use * in KEYNAME for ZUNIONSTORE


问:
Primefaces autocomplete keep selected dropdown value
I have a Primefaces autocomplete box, and have the requirement to keep the value of the dropdown list on the selected value, for example I have a list with 20 elements and I select the 10 element.

If I want to select another value when I select the dropdown It starts on the beginning of the list:

This is my primefaces code:

```<code><p:autoComplete id="transportLAvailable" dropdown="true"
    value="#{remissionOrderReportController.selectedTLineFilter}"
    forceSelection="true" requiredMessage="Some message"
    completeMethod="#{remissionOrderReportController.searchFromTLinesList}"
    var="transportFiltered" itemLabel="#{transportFiltered.name}"
    itemValue="#{transportFiltered}" converter="#{transportLineConverter}">
        <p:ajax event="itemSelect" process="@this"
        listener="#{remissionOrderReportController.findVehicleByTL(transportFiltered)}"/>
</p:autoComplete>
</code>```

I don't have problems saving the values, just with the view.

¿Is there a way to do this on an attribute of p:autoComplete or javascript?

答:
The trick is to simply include the current value at the top of the returned list. I do it like this:

```<code>public List<T> autoCompleteItems(final String query) {
  List<T> results = ...; // Find results for the query
  addBoundValue(Components.getCurrentComponent(), results);
  return results;
}

protected void addBoundValue(UIInput input, List<T> results) {
  if (input.getValue() != null && typeTclass.isAssignableFrom(input.getValue().getClass())) {
    T bound = typeTclass.cast(input.getValue());
    results.remove(bound); // If it's already in the list, remove it first
    results.add(0, bound); // Add the value at the top of the list
  }
}
</code>```

This code comes from a generic bean which uses the type of the list as a parameter (type is set in the constructor to typeTclass).

Please note that I'm using OmniFaces to get the current component. It will get you the the p:autoComplete component, from which you can read the value.

If you can't use OmniFaces, please read How to find out the calling component in the getter method?

Body:
I have a Primefaces autocomplete box, and have the requirement to keep the value of the dropdown list on the selected value, for example I have a list with 20 elements and I select the 10 element.

If I want to select another value when I select the dropdown It starts on the beginning of the list:

This is my primefaces code:

I don't have problems saving the values, just with the view.

¿Is there a way to do this on an attribute of p:autoComplete or javascript?

Body:
The trick is to simply include the current value at the top of the returned list. I do it like this:

public List<T> autoCompleteItems(final String query) {
  List<T> results = ...; // Find results for the query
  addBoundValue(Components.getCurrentComponent(), results);
  return results;
}

protected void addBoundValue(UIInput input, List<T> results) {
  if (input.getValue() != null && typeTclass.isAssignableFrom(input.getValue().getClass())) {
    T bound = typeTclass.cast(input.getValue());
    results.remove(bound); // If it's already in the list, remove it first
    results.add(0, bound); // Add the value at the top of the list
  }
}

This code comes from a generic bean which uses the type of the list as a parameter (type is set in the constructor to typeTclass).

Please note that I'm using OmniFaces to get the current component. It will get you the the p:autoComplete component, from which you can read the value.

If you can't use OmniFaces, please read How to find out the calling component in the getter method?


问:
Manually get the contents of a file in Spring boot 2
I have a file under src/main/resources/static/css/ called my.css that I'm trying to load as a String, but I can't for the life of me get Spring to find this file that's supposedly statically loaded already in the classpath.

```<code>    private String getCss(String cssFileName) {
        try {
            File file = new ClassPathResource("classpath:" + cssFileName + ".css").getFile();
            return new String(Files.readAllBytes(Paths.get(file.getPath())));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "css not found";
    }
}
</code>```

I've tried various webconfigs, resource loaders, paths and patterns but I just cannot get this to work. How do I find a file in my resources? I'd expect some kind of Resources.getResource("name.type") type of thing which already has a tree with all the resources from the resource folder in it listed.

答:
I remember getting stuck with the same problem when i needed to load this xml/json file.
Here is how i solved it - </p>

```<code>String sorting;
this.sorting = org.apache.commons.io.IOUtils.toString((getClass().getClassLoader().getResource("order.json")),
                    StandardCharsets.UTF_8.name());
</code>```

Body:
I have a file under src/main/resources/static/css/ called my.css that I'm trying to load as a String, but I can't for the life of me get Spring to find this file that's supposedly statically loaded already in the classpath.

    private String getCss(String cssFileName) {
        try {
            File file = new ClassPathResource("classpath:" + cssFileName + ".css").getFile();
            return new String(Files.readAllBytes(Paths.get(file.getPath())));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "css not found";
    }
}

I've tried various webconfigs, resource loaders, paths and patterns but I just cannot get this to work. How do I find a file in my resources? I'd expect some kind of Resources.getResource("name.type") type of thing which already has a tree with all the resources from the resource folder in it listed.

Body:
I remember getting stuck with the same problem when i needed to load this xml/json file.
Here is how i solved it -

String sorting;
this.sorting = org.apache.commons.io.IOUtils.toString((getClass().getClassLoader().getResource("order.json")),
                    StandardCharsets.UTF_8.name());


问:
Angular 2 Scroll to top on Route Change
In my Angular 2 app when I scroll down a page and click the link at the bottom of the page, it does change the route and takes me to the next page but it doesn't scroll to the top of the page. As a result, if the first page is lengthy and 2nd page has few contents, it gives an impression that the 2nd page lacks the contents. Since the contents are visible only if a user scrolls to the top of the page.

I can scroll the window to the top of the page in ngInit of the component but, is there any better solution that can automatically handle all routes in my app?

答:
In addition to the perfect answer provided by @Guilherme Meireles as shown below,
you could tweak your implementation by adding smooth scroll as shown below

```<code> import { Component, OnInit } from '@angular/core';
    import { Router, NavigationEnd } from '@angular/router';

    @Component({
        selector: 'my-app',
        template: '<ng-content></ng-content>',
    })
    export class MyAppComponent implements OnInit {
        constructor(private router: Router) { }

        ngOnInit() {
            this.router.events.subscribe((evt) => {
                if (!(evt instanceof NavigationEnd)) {
                    return;
                }
                window.scrollTo(0, 0)
            });
        }
    }
</code>```

then add the snippet below

```<code> html {
      scroll-behavior: smooth;
    }
</code>```

to your styles.css

Title: Angular 2 Scroll to top on Route Change

Body:
In addition to the perfect answer provided by @Guilherme Meireles as shown below,
you could tweak your implementation by adding smooth scroll as shown below

 import { Component, OnInit } from '@angular/core';
    import { Router, NavigationEnd } from '@angular/router';

    @Component({
        selector: 'my-app',
        template: '<ng-content></ng-content>',
    })
    export class MyAppComponent implements OnInit {
        constructor(private router: Router) { }

        ngOnInit() {
            this.router.events.subscribe((evt) => {
                if (!(evt instanceof NavigationEnd)) {
                    return;
                }
                window.scrollTo(0, 0)
            });
        }
    }

then add the snippet below

 html {
      scroll-behavior: smooth;
    }

to your styles.css


问:
Getting mouse-position relatively to a control
I'm trying to find a way to get the mouse position relatively to the upper left corner of a control, is there a way to accomplish that?</p>

答: Call MyControl.PointToClient() passing Cursor.Position.


问:
How to deploy spring boot app which uses postgres database on kubernetes?
I used this command to deploy my spring boot application

```<code>sudo kubectl run mykubernetes-springboot
--image=glgelopfalcon/springboot_docker_maven:0.0.1-SNAPSHOT --port=8080
</code>```

Deplyment is created but when i check logs by

```<code>kubectl logs pod podname
</code>```

It giving exception as

```<code>Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
</code>```

I installed postgres on my local machine.

Test for semah answer
postgres.yaml

```<code>kind: Service
apiVersion: v1
metadata:
  name: postgres-svc
  namespace: default
spec:
  type: ExternalName
  externalName: 10.0.2.2
</code>```

kubectl get svc gives

```<code>postgres-svc       ExternalName   <none>           10.0.2.2      <none>           2m12s
</code>```

Spring boot app deployement logs give

```<code>IOException occurred while connecting to postgres-svc.external.svc:5432
java.net.UnknownHostException: postgres-svc.external.svc
</code>```

答:
If you are trying to connect to DB installed on your local machine and not in kubernetes it is normal to have this error because localhost inside pod this not means your local machine , so can you tell where your db is running ?

try this as you confirmed that you run in local :

```<code>apiVersion: v1
kind: Service
metadata:
name: mysql-db-svc
spec:
ports:
- port: 5432
</code>```

and add endpoint to this service :

```<code>apiVersion: v1
kind: Endpoints
metadata:
name: mysql-db-svc
subsets:
- addresses:
 - ip: 10.0.2.2
 ports:
 - port: 5432
</code>```

then access it using :

```<code>url=jdbc:postgresql://mysql-db-svc/databasename
</code>```

Body:
I used this command to deploy my spring boot application

sudo kubectl run mykubernetes-springboot
--image=glgelopfalcon/springboot_docker_maven:0.0.1-SNAPSHOT --port=8080

Deplyment is created but when i check logs by

kubectl logs pod podname

It giving exception as

Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.

I installed postgres on my local machine.

Test for semah answer
postgres.yaml

kind: Service
apiVersion: v1
metadata:
  name: postgres-svc
  namespace: default
spec:
  type: ExternalName
  externalName: 10.0.2.2

kubectl get svc gives

postgres-svc       ExternalName   <none>           10.0.2.2      <none>           2m12s

Spring boot app deployement logs give

IOException occurred while connecting to postgres-svc.external.svc:5432
java.net.UnknownHostException: postgres-svc.external.svc

Body:
If you are trying to connect to DB installed on your local machine and not in kubernetes it is normal to have this error because localhost inside pod this not means your local machine , so can you tell where your db is running ?

try this as you confirmed that you run in local :

apiVersion: v1
kind: Service
metadata:
name: mysql-db-svc
spec:
ports:
- port: 5432

and add endpoint to this service :

apiVersion: v1
kind: Endpoints
metadata:
name: mysql-db-svc
subsets:
- addresses:
 - ip: 10.0.2.2
 ports:
 - port: 5432

then access it using :

url=jdbc:postgresql://mysql-db-svc/databasename


问:
Real World Haskell book - asymptotic complexity of Logger monad example
I just reached Chapter 14 of Real World Haskell and was wondering about this yesterday.

In the Logger monad example, the bind function is implemented as follows:

```<code>-- (>>=) :: Logger a -> (a -> Logger b) -> Logger b
    m >>= k = let (a, w) = execLogger m
                  n      = k a
                  (b, x) = execLogger n
              in Logger (b, w ++ x)
</code>```

where the 2nd element in the injector function contains our log messages, which are continuously being appended using ++. (Read online around here for more context.)

My question is.. wouldn't that make the runtime complexity using this Logger quadratic to the number of messages?

If I'm wrong, please help provide the correct analysis and big oh notation.

If I'm right, I'm hoping people who have more experience/insights with Haskell and the book can tell me some reasons of choosing that implementation, and why it is ok.
In the previous chapter of the book there's a section that says this way of appending of list is bad, and teaches us the difference list technique. Why is this not being used here?

BTW I love the book, it's going to be a book I'll read cover to cover since a long long time.

答:
For comparison, Haskell Platform's monad library package "mtl" gets Writer from packages "transformers".  The implementation of Writer for all Monoid types is in the source near here.  The instance uses mappend instead of (++):</p>

```<code>instance (Monoid w, Monad m) => Monad (WriterT w m) where
    return a = WriterT $ return (a, mempty)
    m >>= k  = WriterT $ do
        ~(a, w)  <- runWriterT m
        ~(b, w') <- runWriterT (k a)
        return (b, w `mappend` w')
    fail msg = WriterT $ fail msg
</code>```

Body:
I just reached Chapter 14 of Real World Haskell and was wondering about this yesterday.

In the Logger monad example, the bind function is implemented as follows:

-- (>>=) :: Logger a -> (a -> Logger b) -> Logger b
    m >>= k = let (a, w) = execLogger m
                  n      = k a
                  (b, x) = execLogger n
              in Logger (b, w ++ x)

where the 2nd element in the injector function contains our log messages, which are continuously being appended using ++. (Read online around here for more context.)

My question is.. wouldn't that make the runtime complexity using this Logger quadratic to the number of messages?

If I'm wrong, please help provide the correct analysis and big oh notation.

If I'm right, I'm hoping people who have more experience/insights with Haskell and the book can tell me some reasons of choosing that implementation, and why it is ok.
In the previous chapter of the book there's a section that says this way of appending of list is bad, and teaches us the difference list technique. Why is this not being used here?

BTW I love the book, it's going to be a book I'll read cover to cover since a long long time.

Body:
For comparison, Haskell Platform's monad library package "mtl" gets Writer from packages "transformers".  The implementation of Writer for all Monoid types is in the source near here.  The instance uses mappend instead of (++):

instance (Monoid w, Monad m) => Monad (WriterT w m) where
    return a = WriterT $ return (a, mempty)
    m >>= k  = WriterT $ do
        ~(a, w)  <- runWriterT m
        ~(b, w') <- runWriterT (k a)
        return (b, w `mappend` w')
    fail msg = WriterT $ fail msg


问:
How do I go back to the finished activity dynamically?
For example, user passed between activities A to B. Now finish A and pass B to C, then finish B. Then click to the back button and go B again. Because B is the activity that the user comes from to current(ActivityC) activity.If the user go to the C from A directly, then finish A. If press the back button, then goes to the A again. Because A is the activity that the user comes from to current(ActivityC) activity.
   I want to set the onBackPress button to start activities that started before orderly. If I don't finish activities that started before when I start another activity, I can show the activity that started before with finish() current activity. This is possible. Because I don't finish any activity. So finish() current activity will cause show activity that started before. But, RAM will be overload when I open 50 activities may be. So because of this problem I need to finish() activity that started before. On the other hand, I want to start the activity that started before orderly when clicking to the back button. For example

```<code>  ActivityA --> ActivityB --> ActivityC --> ActivityD
</code>```

In this scenario, I finish ActivityA, ActivityB, ActivityC orderly. But I want to start ActivityC back press of the ActivityD and I want to start ActivityB on the back press of ActivityC.

Lastly, I have a complex path in the application. And, I navigate to the ActivityD and I finished the ActivityF when my current activity is ActivityF

```<code>ActivityF --> ActivityD
ActivityF finished
</code>```

Current activity:

```<code>ActivityD
</code>```

In this scenario, I want to start the ActivityF not the ActivityC on back button of the ActivityD.

Normally:

```<code>ActivityA --> ActivityB --> ActivityC --> ActivityD /// click back button
ActivityA --> ActivityB --> ActivityC /// click back button
ActivityA --> ActivityB /// click back button
ActivityA
</code>```

or

```<code>ActivityA --> ActivityF --> ActivityD /// click back button
ActivityA --> ActivityF /// click back button
ActivityA
</code>```

But I want to generate this scenario:

```<code>ActivityA
--> ActivityB
--> ActivityC
--> ActivityD /// click back button
ActivityC <-- /// click back button
ActivityB <-- /// click back button
ActivityA
</code>```

or

```<code>ActivityA
--> ActivityF
--> ActivityD /// click back button
ActivityF <-- /// click back button
ActivityA <--
</code>```

答:
You should use Stack to keep track of your Activities.
Stack in Android

Just push the current Activity before Intent to next Activity, and pop the current Activity in the onBackPressed() method.

You can save the Stack on SharedPreference.

EDIT:

This is the code. I used a DataHandler class to save the Stack.

DataHandler.java

```<code>public class DataHandler {
private static DataHandler mDataHandler;
private Deque<Intent> stack = new ArrayDeque<>();

private DataHandler() {
}

public static DataHandler getInstance(){
    if(mDataHandler == null){
        mDataHandler = new DataHandler();
    }
    return mDataHandler;
}

public Deque<Intent> getStack() {
    return stack;
}

public void setStack(Deque<Intent> stack) {
    this.stack = stack;
}
}
</code>```

M1Activity.java

```<code>public class M1Activity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_m1);
    Button btn = findViewById(R.id.btn);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(M1Activity.this,M2Activity.class);
            startActivity(intent);
            DataHandler.getInstance().getStack().push(intent);
            finish();
        }
    });
}

@Override
public void onBackPressed() {
    super.onBackPressed();
    if (DataHandler.getInstance().getStack().size() > 0){
        Intent intent = DataHandler.getInstance().getStack().pop();
        startActivity(intent);
    }
}
}
</code>```

Just like M1Activity, you have to push and pop intent from Stack in every Activity.

Body:
For example, user passed between activities A to B. Now finish A and pass B to C, then finish B. Then click to the back button and go B again. Because B is the activity that the user comes from to current(ActivityC) activity.If the user go to the C from A directly, then finish A. If press the back button, then goes to the A again. Because A is the activity that the user comes from to current(ActivityC) activity.
   I want to set the onBackPress button to start activities that started before orderly. If I don't finish activities that started before when I start another activity, I can show the activity that started before with finish() current activity. This is possible. Because I don't finish any activity. So finish() current activity will cause show activity that started before. But, RAM will be overload when I open 50 activities may be. So because of this problem I need to finish() activity that started before. On the other hand, I want to start the activity that started before orderly when clicking to the back button. For example

  ActivityA --> ActivityB --> ActivityC --> ActivityD

In this scenario, I finish ActivityA, ActivityB, ActivityC orderly. But I want to start ActivityC back press of the ActivityD and I want to start ActivityB on the back press of ActivityC.

Lastly, I have a complex path in the application. And, I navigate to the ActivityD and I finished the ActivityF when my current activity is ActivityF

ActivityF --> ActivityD
ActivityF finished

Current activity:

ActivityD

In this scenario, I want to start the ActivityF not the ActivityC on back button of the ActivityD.

Normally:

ActivityA --> ActivityB --> ActivityC --> ActivityD /// click back button
ActivityA --> ActivityB --> ActivityC /// click back button
ActivityA --> ActivityB /// click back button
ActivityA

or

ActivityA --> ActivityF --> ActivityD /// click back button
ActivityA --> ActivityF /// click back button
ActivityA

But I want to generate this scenario:

ActivityA
--> ActivityB
--> ActivityC
--> ActivityD /// click back button
ActivityC <-- /// click back button
ActivityB <-- /// click back button
ActivityA

or

ActivityA
--> ActivityF
--> ActivityD /// click back button
ActivityF <-- /// click back button
ActivityA <--

Body:
You should use Stack to keep track of your Activities.
Stack in Android

Just push the current Activity before Intent to next Activity, and pop the current Activity in the onBackPressed() method.

You can save the Stack on SharedPreference.

EDIT:

This is the code. I used a DataHandler class to save the Stack.

DataHandler.java

public class DataHandler {
private static DataHandler mDataHandler;
private Deque<Intent> stack = new ArrayDeque<>();

private DataHandler() {
}

public static DataHandler getInstance(){
    if(mDataHandler == null){
        mDataHandler = new DataHandler();
    }
    return mDataHandler;
}

public Deque<Intent> getStack() {
    return stack;
}

public void setStack(Deque<Intent> stack) {
    this.stack = stack;
}
}

M1Activity.java

public class M1Activity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_m1);
    Button btn = findViewById(R.id.btn);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(M1Activity.this,M2Activity.class);
            startActivity(intent);
            DataHandler.getInstance().getStack().push(intent);
            finish();
        }
    });
}

@Override
public void onBackPressed() {
    super.onBackPressed();
    if (DataHandler.getInstance().getStack().size() > 0){
        Intent intent = DataHandler.getInstance().getStack().pop();
        startActivity(intent);
    }
}
}

Just like M1Activity, you have to push and pop intent from Stack in every Activity.


问:
Get all child views inside LinearLayout at once
I have a LinearLayout, which contains several child TextViews. How can I get child views of that LinerLayout using a loop?

答:
It is easier with Kotlin using for-in loop:

```<code>for (childView in ll.children) {
     //childView is a child of ll
}
</code>```

Here ll is id of LinearLayout defined in layout XML.

Body:
It is easier with Kotlin using for-in loop:

for (childView in ll.children) {
     //childView is a child of ll
}

Here ll is id of LinearLayout defined in layout XML.


问:
UIGesturerecognizer is not working on UIView
When I am tapping on UIView but Gesture is not working.

```<code>override func viewDidLoad() {
        super.viewDidLoad()

        let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
        viewForSHadow.isUserInteractionEnabled = true
        viewForSHadow.addGestureRecognizer(tap)

        // Do any additional setup after loading the view.
    }

func handleTap(_sender: UITapGestureRecognizer) {
        print("---------View Tapped--------")
        viewForSHadow.isHidden = true
        viewForAlert.isHidden = true
    }

</code>```

I just want to perform this action on UIView tap.

答: You may check in the debug view hierarchy if anything with alpha = 0 is overlapping your viewForSHadow.

Body:
When I am tapping on UIView but Gesture is not working.

override func viewDidLoad() {
        super.viewDidLoad()

        let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
        viewForSHadow.isUserInteractionEnabled = true
        viewForSHadow.addGestureRecognizer(tap)

        // Do any additional setup after loading the view.
    }

func handleTap(_sender: UITapGestureRecognizer) {
        print("---------View Tapped--------")
        viewForSHadow.isHidden = true
        viewForAlert.isHidden = true
    }

I just want to perform this action on UIView tap.


问:
Check Name Availability of Azure Data Factory (ADF), Time Series Insights (TSI) and Stream Analytics Job resources
I am looking for a API or documentation for querying for name availability of Azure Data Factory (ADF), Time Series Insights (TSI) and Stream Analytics Job resources similar to https://learn.microsoft.com/en-us/rest/api/keyvault/vaults/checknameavailability.

I have tried looking at azure-arm-datafactory, azure-arm-streamanalytics node libraries but couldn't find functionality to check name availability of resources.

I am looking for something similar to below..

```<code>import KeyVaultMangementClient from 'azure-arm-keyvault';
const client = new KeyVaultMangementClient(this._credentials, this._subscriptionId);
        return client.vaults.checkNameAvailability({name: keyVaultName})
            .then((result: any) => {
                console.log(result.nameAvailable);
                return Promise.resolve(result.nameAvailable);
            });
</code>```

答: AFAIK this (check name availability) feature is currently unsupported for ADF, TSI, Stream Analytics. So I would recommend you to please add a new feature request on uservoice with your suggestion(s) and let us know the link when you do it so that others can vote as well and which would in turn would raise visibility and priority on it.</p>

Body:
I am looking for a API or documentation for querying for name availability of Azure Data Factory (ADF), Time Series Insights (TSI) and Stream Analytics Job resources similar to https://learn.microsoft.com/en-us/rest/api/keyvault/vaults/checknameavailability.

I have tried looking at azure-arm-datafactory, azure-arm-streamanalytics node libraries but couldn't find functionality to check name availability of resources.

I am looking for something similar to below..

import KeyVaultMangementClient from 'azure-arm-keyvault';
const client = new KeyVaultMangementClient(this._credentials, this._subscriptionId);
        return client.vaults.checkNameAvailability({name: keyVaultName})
            .then((result: any) => {
                console.log(result.nameAvailable);
                return Promise.resolve(result.nameAvailable);
            });


问:
Is HAML a Better Tool for Experienced Ruby/Rails Developers?
One of the joys of being a new Ruby on Rails student/developer is the constant discovery of new Gems to make my life more fun or easier. Recently, I "discovered" HAML, which appears to be a fantastic tool for making ERB code even more readable than it already is. However, I wonder if it is a good idea for newer developers, like myself, to embrace a tool like HAML early on, or if it would be smarter to hold off until my expertise in plain Ruby / Rails code has matured. My worry, I suppose, is that embracing a tool like HAML too early might impede my full understanding of Ruby through the coding "shortcuts" it offers. What do you experienced coders say? </p>

答:
Here is what I would do:

Learn HTML if you don't already know it well

Learn how to use erb with HTML.  That might take you 30 minutes.  You just drop ruby code inside <% %> and if you want to output a variable's value you use it with equals sign: <%= %>.  There is really not much to it.  But like others said, you need to at least understand how it works since it is so widely used in view code examples... and it is also used in yaml files.

Then spend a few hours learning HAML and use it instead of erb.  Aside from maybe using erb on javascript partials and in yaml files, I never thought twice about using it after learning HAML.

IMO, HAML is way cleaner, less prone to errors and much shorter than writing erb.  HAML closes the tags for you so you dont have to put it in your code, it forces you to write correctly indented code and it has some great shortcuts for adding classes and ids to HTML tags.

I would be interested to hear any use cases where you guys find html.erb better than html.haml.  Like I said, the only place that I don't like to use it is with javascript code... as I find the indentation rules get in the way sometimes.


问:
How do I get names of children from Firebase to listview Android?
I am new to working with Firebase. How do I get the names of the children from my Firebase to a listview?

Here is my database:

Here is my code, but it does not work.

```<code>public class Education extends AppCompatActivity {

    private DatabaseReference fNotesDatabase;
    ListView listView;
    ArrayList<String> arraylist = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_education);

        Firebase.setAndroidContext(this);
        fNotesDatabase = FirebaseDatabase.getInstance().getReference().child("Notes").child("education").child();
        listView = (ListView) findViewById(R.id.listview);
        final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arraylist);

        listView.setAdapter(arrayAdapter);

        fNotesDatabase.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                Map<String, Object> map = new HashMap<String, Object>();
                arraylist.add(map.values().toString());
                arrayAdapter.notifyDataSetChanged();
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {
                Map<String, Object> map = new HashMap<String, Object>();
                arraylist.add(map.values().toString());
            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }
}
</code>```

答:
If you want to retrieve the direct children under Notes, then try the following:

```<code>ArrayAdapter adapter;
ListView listView;
ArrayList<String> arraylist = new ArrayList<>();

listView = findViewById(R.id.listview);
fNotesDatabase = FirebaseDatabase.getInstance().getReference().child("Notes");

fNotesDatabase.addSingleValueEventListener(new ValueEventListener() {

    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

        for(DataSnapshot datas: dataSnapshot.getChildren()) {
            String values = datas.getKey();
            arraylist.add(values);
            adapter = new ArrayAdapter(Education.this, android.R.layout.simple_list_item_single_choice, arraylist);
            listView.setAdapter(adapter);
        }
    }

    @Override
    public void onCancelled(FirebaseError firebaseError) {

    }
});

</code>```

First add reference at child Notes and then loop inside of it and retrieve the keys using getKey()

Body:
I am new to working with Firebase. How do I get the names of the children from my Firebase to a listview?

Here is my database:

Here is my code, but it does not work.

public class Education extends AppCompatActivity {

    private DatabaseReference fNotesDatabase;
    ListView listView;
    ArrayList<String> arraylist = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_education);

        Firebase.setAndroidContext(this);
        fNotesDatabase = FirebaseDatabase.getInstance().getReference().child("Notes").child("education").child();
        listView = (ListView) findViewById(R.id.listview);
        final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arraylist);

        listView.setAdapter(arrayAdapter);

        fNotesDatabase.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                Map<String, Object> map = new HashMap<String, Object>();
                arraylist.add(map.values().toString());
                arrayAdapter.notifyDataSetChanged();
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {
                Map<String, Object> map = new HashMap<String, Object>();
                arraylist.add(map.values().toString());
            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }
}

Body:
If you want to retrieve the direct children under Notes, then try the following:

ArrayAdapter adapter;
ListView listView;
ArrayList<String> arraylist = new ArrayList<>();

listView = findViewById(R.id.listview);
fNotesDatabase = FirebaseDatabase.getInstance().getReference().child("Notes");

fNotesDatabase.addSingleValueEventListener(new ValueEventListener() {

    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

        for(DataSnapshot datas: dataSnapshot.getChildren()) {
            String values = datas.getKey();
            arraylist.add(values);
            adapter = new ArrayAdapter(Education.this, android.R.layout.simple_list_item_single_choice, arraylist);
            listView.setAdapter(adapter);
        }
    }

    @Override
    public void onCancelled(FirebaseError firebaseError) {

    }
});

First add reference at child Notes and then loop inside of it and retrieve the keys using getKey()


问:
How to fix :Trying to get property of non-object in PHP
How to resolve this problem ?

```<code>if (strpos($scripts->item($i)->nodeValue, "test") !== false) { //line 127
    return true
}
</code>```

Notice: Trying to get property of non-object on line 127

答:
Check if values exist at all</p>

```<code>if(!empty($scripts->item($i)->nodeValue))
{
//your code
}
</code>```

Body:
How to resolve this problem ?

if (strpos($scripts->item($i)->nodeValue, "test") !== false) { //line 127
    return true
}

Notice: Trying to get property of non-object on line 127

Body:
Check if values exist at all

if(!empty($scripts->item($i)->nodeValue))
{
//your code
}