问:
How can primitive data types have access to prototype?
How primitive data types (strings, numbers etc.) have access to methods like .toString(). We can even access to their proto's by typing variable.proto but they are not object.

答:
JavaScript automatically converts primitives to String objects, so that it's possible to use String object methods for primitive strings.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String


来源: stackexchange

问:
load balancing for unmanaged instance group
I have one primary vm in an unmanaged instance group. To perform updates and maintenance, I'll add an updated VM to the group and then proceed to remove the existing one to update. I was thinking it shouldn't be any downtime by doing so. However, whenever I make a change to the backend, the server will be unavailable for 30 seconds. How can I avoid this downtime? Is it due to the healthcheck configuration?

This is my healthcheck setup

答:
Enable instance draining. This allows for existing connections to complete and begins the process of sending new traffic to the other instance.

Now you can remove a VM from the instance group without downtime. Wait for the instance draining time plus 60 seconds before modifying the instance.

Enabling connection draining

ContentLicense: CC BY-SA 4.0


问:
Pine Editor If/Else and "Cannot use 'plot' in local scope"
This is my first attempt at coding with Pine Editor, and I'm trying to make make an adjustable moving average ribbon indicator that allows the user to select between increments of 1 and 2. For example, one setting that plots the 5, 6, 7, 8 and 9 averages, and another that plots 6, 8, 10, 12 and 14. I understand I will need to code an if/else condition to determine which series to plot, however, I get the error "Cannot use 'plot' in local scope" when trying this. Can someone advise me of a workaround please?</p>
```<code>src = input(title="Source", type=source, defval=close)
increment= input(defval='1', title = "Increment", options =['1', '2'])
matype= input(defval='SMA', title = "Weighting", options =['SMA', 'EMA', 'WMA', 'VWMA','RMA', 'ALMA'])
getma(lngth)=>
    _ret = matype == 'SMA' ? sma(close, lngth) : matype == 'EMA' ? ema(close, lngth) : matype == 'WMA' ? wma(close, lngth) : matype == 'VWMA' ? vwma(close, lngth) : matype == 'RMA' ? rma(close, lngth) : alma(close, lngth, 0, 2)

if increment== "1"
    plot(getma(5), title="05", linewidth=1, color=src >= getma(5) ? green : red, transp=88)
    plot(getma(6), title="06", linewidth=1, color=src >= getma(6) ? green : red, transp=88)
    plot(getma(7), title="07", linewidth=1, color=src >= getma(7) ? green : red, transp=88)
    plot(getma(8), title="08", linewidth=1, color=src >= getma(8) ? green : red, transp=88)
    plot(getma(9), title="09", linewidth=1, color=src >= getma(9) ? green : red, transp=88)
    plot(getma(10), title="10", linewidth=1, color=src >= getma(10) ? green : red, transp=88)

else if increment== "2"
    plot(getma(6), title="06", linewidth=1, color=src >= getma(6) ? green : red, transp=88)
    plot(getma(8), title="08", linewidth=1, color=src >= getma(8) ? green : red, transp=88)
    plot(getma(10), title="10", linewidth=1, color=src >= getma(10) ? green : red, transp=88)
    plot(getma(12), title="12", linewidth=1, color=src >= getma(12) ? green : red, transp=88)
    plot(getma(14), title="14", linewidth=1, color=src >= getma(14) ? green : red, transp=88)
    plot(getma(16), title="16", linewidth=1, color=src >= getma(16) ? green : red, transp=88
</code>```

答:
So, the error message is clear. You cannot use the plot() function in local scope. What you can do is, apply your condition to the series argument of your plot() calls.

```<code>plot(increment== "1" ? getma(5) : na, title="05", linewidth=1, color=src >= getma(5) ? green : red, transp=88)
</code>```

So, if increment== "1" is true, it will plot the value of getma(5), else, it will not plot anything (na).

Body:
This is my first attempt at coding with Pine Editor, and I'm trying to make make an adjustable moving average ribbon indicator that allows the user to select between increments of 1 and 2. For example, one setting that plots the 5, 6, 7, 8 and 9 averages, and another that plots 6, 8, 10, 12 and 14. I understand I will need to code an if/else condition to determine which series to plot, however, I get the error "Cannot use 'plot' in local scope" when trying this. Can someone advise me of a workaround please?

src = input(title="Source", type=source, defval=close)
increment= input(defval='1', title = "Increment", options =['1', '2'])
matype= input(defval='SMA', title = "Weighting", options =['SMA', 'EMA', 'WMA', 'VWMA','RMA', 'ALMA'])
getma(lngth)=>
    _ret = matype == 'SMA' ? sma(close, lngth) : matype == 'EMA' ? ema(close, lngth) : matype == 'WMA' ? wma(close, lngth) : matype == 'VWMA' ? vwma(close, lngth) : matype == 'RMA' ? rma(close, lngth) : alma(close, lngth, 0, 2)

if increment== "1"
    plot(getma(5), title="05", linewidth=1, color=src >= getma(5) ? green : red, transp=88)
    plot(getma(6), title="06", linewidth=1, color=src >= getma(6) ? green : red, transp=88)
    plot(getma(7), title="07", linewidth=1, color=src >= getma(7) ? green : red, transp=88)
    plot(getma(8), title="08", linewidth=1, color=src >= getma(8) ? green : red, transp=88)
    plot(getma(9), title="09", linewidth=1, color=src >= getma(9) ? green : red, transp=88)
    plot(getma(10), title="10", linewidth=1, color=src >= getma(10) ? green : red, transp=88)

else if increment== "2"
    plot(getma(6), title="06", linewidth=1, color=src >= getma(6) ? green : red, transp=88)
    plot(getma(8), title="08", linewidth=1, color=src >= getma(8) ? green : red, transp=88)
    plot(getma(10), title="10", linewidth=1, color=src >= getma(10) ? green : red, transp=88)
    plot(getma(12), title="12", linewidth=1, color=src >= getma(12) ? green : red, transp=88)
    plot(getma(14), title="14", linewidth=1, color=src >= getma(14) ? green : red, transp=88)
    plot(getma(16), title="16", linewidth=1, color=src >= getma(16) ? green : red, transp=88

Body:
So, the error message is clear. You cannot use the plot() function in local scope. What you can do is, apply your condition to the series argument of your plot() calls.

plot(increment== "1" ? getma(5) : na, title="05", linewidth=1, color=src >= getma(5) ? green : red, transp=88)

So, if increment== "1" is true, it will plot the value of getma(5), else, it will not plot anything (na).


问:
how do i make googletrans to work for a simple hello world translation?
Python 3.10.2 (tags/v3.10.2:a58ebcc, Jan 17 2022, 14:12:15) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.</p>
```<code>from googletrans import Translator
translator = Translator()
translator.translate('olá, mundo')
</code>```
```<code>Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    translator.translate('olá, mundo')
  File "C:\Users\Fernando\AppData\Local\Programs\Python\Python310\lib\site-packages\googletrans\client.py", line 182, in translate
    data = self._translate(text, dest, src, kwargs)
  File "C:\Users\Fernando\AppData\Local\Programs\Python\Python310\lib\site-packages\googletrans\client.py", line 78, in _translate
    token = self.token_acquirer.do(text)
  File "C:\Users\Fernando\AppData\Local\Programs\Python\Python310\lib\site-packages\googletrans\gtoken.py", line 194, in do
    self._update()
  File "C:\Users\Fernando\AppData\Local\Programs\Python\Python310\lib\site-packages\googletrans\gtoken.py", line 62, in _update
    code = self.RE_TKK.search(r.text).group(1).replace('var ', '')
AttributeError: 'NoneType' object has no attribute 'group'
</code>```

答: The traceback shows that line 62 in gtoken.update is not prepared to handle the case that seach return None instead of a match object.  Report the code and traceback to the googletrans authors.</p>

Body:
Python 3.10.2 (tags/v3.10.2:a58ebcc, Jan 17 2022, 14:12:15) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.

from googletrans import Translator
translator = Translator()
translator.translate('olá, mundo')

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    translator.translate('olá, mundo')
  File "C:\Users\Fernando\AppData\Local\Programs\Python\Python310\lib\site-packages\googletrans\client.py", line 182, in translate
    data = self._translate(text, dest, src, kwargs)
  File "C:\Users\Fernando\AppData\Local\Programs\Python\Python310\lib\site-packages\googletrans\client.py", line 78, in _translate
    token = self.token_acquirer.do(text)
  File "C:\Users\Fernando\AppData\Local\Programs\Python\Python310\lib\site-packages\googletrans\gtoken.py", line 194, in do
    self._update()
  File "C:\Users\Fernando\AppData\Local\Programs\Python\Python310\lib\site-packages\googletrans\gtoken.py", line 62, in _update
    code = self.RE_TKK.search(r.text).group(1).replace('var ', '')
AttributeError: 'NoneType' object has no attribute 'group'


问:
How npm start runs a server on port 8000
I recently used a angular-seed folder from github for angular application development. In some previous angularjs tutorial there was a script folder and a server.js file in the angular-seed folder which had all the configuration for running the node server. So how does npm now just start running a node server and where is all the configuration of that node server?</p>

答:
```<code>npm run start -- -p 8000
</code>```

8000 is port number you can change your port number

ContentLicense: CC BY-SA 3.0

Body:
npm run start -- -p 8000

8000 is port number you can change your port number


问:
Python: TypeError: 'module' object is not subscriptable
I was watching this tutorial. I copied over the stuff he wrote, but with some changes in the variables and other stuff. Then I got the error (The error is below).

Here's the code (main.py):

```<code>import nltk
from nltk import *
import numpy
import tflearn
import json
import random
import tensorflow

stemmer = LancasterStemmer()
prefix = "[Bot]"

trainer_load = json.load(open("trainer.json"))

words = []
labels = []
docs_a = []
docs_b = []

for trainer in data["dictionary"]: # Error here
    for inputs in trainer["inputs"]:
        words_tokenize = nltk.word_tokenize(inputs)
        words.extend(words_tokenize)
        docs_a.append(inputs)
        docs_b.append(trainer["tag"])

    if trainer["tag"] not in labels:
        labels.append(trainer["tag"])

words = [stemmer.stem(w.lower()) for w in words]
words = sorted(list(set(words)))

labels = sorted(labels)

training = []
output = []

out_empty = [0 for _ in range(len(classes))]

for a, doc in enumerate(docs_a):
    bag = []

    words_tokenize = [stemmer.stem(a) for a in doc]

    for a in words:
        if a in words_tokenize:
            bag.append(1)
        else:
            bag.append(0)

    output_row = out_empty[:]
    output_row[classes.index(docs_b[a])] = 1

    training.append(bag)
    output.append(output_row)

training = numpy.array(training)
output = numpy.array(output)
</code>```

Here's the error:

```<code>Traceback (most recent call last):
  File "C:\Users\(I hid my name)\OneDrive\Desktop\Codes\Python codes\Chatbot\main.py", line 19, in <module>
    for trainer in data["dictionary"]:
TypeError: 'module' object is not subscriptable
</code>```

I've searched in my browser and all the answers I found are not related to my question. My JSON file exists, it's in the same folder as the main.py.

This is the JSON file: (trainer.json)

```<code>{"dictionary": [
    {"tag": "greetings",
     "inputs": ["Hi", "Hello", "How are you", "Whats up", "Greetings", "Good day"],
     "responses": ["Hello!", "Hi!", "I'm good! Always good.", "Greetings!", "I know, right!"],
     "context_set": ""
    },
    {"tag": "identity",
     "inputs": ["Who are you", "Who you"],
     "responses": ["I'm a chatting bot built by FighterLoveNoob, he was watching a tutorial while building me"],
     "context_set": ""
    }
]}
</code>```

答:
Explanation:

data is not defined, your json data is loaded in trainer_load.

I was watching this tutorial. I copied over the stuff he wrote, but with some changes in the variables and other stuff. Then I got the error (The error is below).

Change in the variable is the cause of the error. You must change the variable in every occurrence if you want to change, you just changed while defining the variable

In the link you have refered the code is:

```<code>with open('intents.json') as file:
    # Here data is used NOT trainer_load
    # If you want to change data to trainer_load change it every where.
    data = json.load(file)
</code>```

Code:

import nltk
from nltk import *
import numpy
import tflearn
import json
import random
import tensorflow

stemmer = LancasterStemmer()
prefix = "[Bot]"

trainer_load = json.load(open("trainer.json"))

words = []
labels = []
docs_a = []
docs_b = []

#data is not defined, your json data is loaded in trainer_load
for trainer in trainer_load["dictionary"]:
    for inputs in trainer["inputs"]:
        words_tokenize = nltk.word_tokenize(inputs)
        words.extend(words_tokenize)
        docs_a.append(inputs)
        docs_b.append(trainer["tag"])

    if trainer["tag"] not in labels:
        labels.append(trainer["tag"])

words = [stemmer.stem(w.lower()) for w in words]
words = sorted(list(set(words)))

labels = sorted(labels)

training = []
output = []

out_empty = [0 for _ in range(len(classes))]

for a, doc in enumerate(docs_a):
    bag = []

    words_tokenize = [stemmer.stem(a) for a in doc]

    for a in words:
        if a in words_tokenize:
            bag.append(1)
        else:
            bag.append(0)

    output_row = out_empty[:]
    output_row[classes.index(docs_b[a])] = 1

    training.append(bag)
    output.append(output_row)

training = numpy.array(training)
output = numpy.array(output)
```

Body:
I was watching this tutorial. I copied over the stuff he wrote, but with some changes in the variables and other stuff. Then I got the error (The error is below).

Here's the code (main.py):

import nltk
from nltk import *
import numpy
import tflearn
import json
import random
import tensorflow

stemmer = LancasterStemmer()
prefix = "[Bot]"

trainer_load = json.load(open("trainer.json"))

words = []
labels = []
docs_a = []
docs_b = []

for trainer in data["dictionary"]: # Error here
    for inputs in trainer["inputs"]:
        words_tokenize = nltk.word_tokenize(inputs)
        words.extend(words_tokenize)
        docs_a.append(inputs)
        docs_b.append(trainer["tag"])

    if trainer["tag"] not in labels:
        labels.append(trainer["tag"])

words = [stemmer.stem(w.lower()) for w in words]
words = sorted(list(set(words)))

labels = sorted(labels)

training = []
output = []

out_empty = [0 for _ in range(len(classes))]

for a, doc in enumerate(docs_a):
    bag = []

    words_tokenize = [stemmer.stem(a) for a in doc]

    for a in words:
        if a in words_tokenize:
            bag.append(1)
        else:
            bag.append(0)

    output_row = out_empty[:]
    output_row[classes.index(docs_b[a])] = 1

    training.append(bag)
    output.append(output_row)

training = numpy.array(training)
output = numpy.array(output)

Here's the error:

Traceback (most recent call last):
  File "C:\Users\(I hid my name)\OneDrive\Desktop\Codes\Python codes\Chatbot\main.py", line 19, in <module>
    for trainer in data["dictionary"]:
TypeError: 'module' object is not subscriptable

I've searched in my browser and all the answers I found are not related to my question. My JSON file exists, it's in the same folder as the main.py.

This is the JSON file: (trainer.json)

{"dictionary": [
    {"tag": "greetings",
     "inputs": ["Hi", "Hello", "How are you", "Whats up", "Greetings", "Good day"],
     "responses": ["Hello!", "Hi!", "I'm good! Always good.", "Greetings!", "I know, right!"],
     "context_set": ""
    },
    {"tag": "identity",
     "inputs": ["Who are you", "Who you"],
     "responses": ["I'm a chatting bot built by FighterLoveNoob, he was watching a tutorial while building me"],
     "context_set": ""
    }
]}

Body:
Explanation:

data is not defined, your json data is loaded in trainer_load.

I was watching this tutorial. I copied over the stuff he wrote, but with some changes in the variables and other stuff. Then I got the error (The error is below).

Change in the variable is the cause of the error. You must change the variable in every occurrence if you want to change, you just changed while defining the variable

In the link you have refered the code is:

with open('intents.json') as file:
    # Here data is used NOT trainer_load
    # If you want to change data to trainer_load change it every where.
    data = json.load(file)

Code:

import nltk
from nltk import *
import numpy
import tflearn
import json
import random
import tensorflow

stemmer = LancasterStemmer()
prefix = "[Bot]"

trainer_load = json.load(open("trainer.json"))

words = []
labels = []
docs_a = []
docs_b = []

#data is not defined, your json data is loaded in trainer_load
for trainer in trainer_load["dictionary"]:
    for inputs in trainer["inputs"]:
        words_tokenize = nltk.word_tokenize(inputs)
        words.extend(words_tokenize)
        docs_a.append(inputs)
        docs_b.append(trainer["tag"])

    if trainer["tag"] not in labels:
        labels.append(trainer["tag"])

words = [stemmer.stem(w.lower()) for w in words]
words = sorted(list(set(words)))

labels = sorted(labels)

training = []
output = []

out_empty = [0 for _ in range(len(classes))]

for a, doc in enumerate(docs_a):
    bag = []

    words_tokenize = [stemmer.stem(a) for a in doc]

    for a in words:
        if a in words_tokenize:
            bag.append(1)
        else:
            bag.append(0)

    output_row = out_empty[:]
    output_row[classes.index(docs_b[a])] = 1

    training.append(bag)
    output.append(output_row)

training = numpy.array(training)
output = numpy.array(output)


问:
How to programatically add product images in django oscar?
I am currently programatically importing products into my product catalog, however, I am having difficulty uploading images for each product. Here's what my code looks like:

# frobshop/custom_utils/product_importer.py

from oscar.apps.catalogue.models import Product
...

for product in my_product_import_list:
    ...
    product_entry = Product()
    product_entry.title = my_product_title
    product_entry.product_class = my_product_class
    product_entry.category = my_category
    product_entry.primary_image = "product_images/my_product_filename.jpg"
    product_entry.save()
```

<p>The details such as product title and product class are successfully saved when I check using the development server, however, I am unsure how to set an image for each product.</p>

<p>The entire <code>product_images</code> folder was initially located outside of my <code>media</code> directory, but since I wasn't getting any results, I copy pasted the entire folder of my images into the <code>media</code> directory but still with no results.  I am assuming that quite a number of steps are being skipped, and maybe there's a convention on how to arrange images in the media directory.  However, I am not sure where to find these steps and conventions.</p>

<p>Here's the portion of my <code>settings.py</code> file that deals with my installed apps, the media directory, and static files:</p>

<pre class="lang-py prettyprint-override"><code># frobshop/frobshop/settings.py

...

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',

    'django.contrib.sites',

    'django.contrib.messages',
    'django.contrib.staticfiles',

    'django.contrib.flatpages',

    'compressor',
    'widget_tweaks',
] + get_core_apps(['custom_apps.shipping', 'custom_apps.payment', 'custom_apps.checkout'])

...

STATIC_ROOT = 'static'
STATIC_URL = '/static/'
MEDIA_ROOT = 'media'
MEDIA_URL = '/media/'

</code>```

For further clarity, here's my urls.py

from django.contrib import admin
from django.urls import path
from django.conf.urls import include, url
from oscar.app import application
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    url(r'^i18n/', include('django.conf.urls.i18n')),
    path('admin/', admin.site.urls),
    url(r'', application.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
```

答:
Not entirely sure how helpful this will be to anyone, but I was getting a SuspiciousFileOperation Exception when using @ruddra's answer here, even though I was using a tempfile within the media root...

```<code>File "/Users/user/Documents/project/venv/lib/python3.7/site-packages/django/core/files/utils.py", line 19, in validate_file_name
    "Detected path traversal attempt in '%s'" % name
django.core.exceptions.SuspiciousFileOperation: Detected path traversal attempt in '/Users/user/Documents/project/media/images/tmp6xem6hvs'
</code>```

Fixed by first saving the image (got the idea from this SO answer), then saving the product image:

import tempfile
from django.core.files.images import ImageFile
...
lf = tempfile.NamedTemporaryFile(dir='media')
f = open('<full_path_to_project>/media/images/my_product_filename.jpg', 'rb')
lf.write(f.read())
image = ImageFile(lf)
product_image = ProductImage()
product_image.caption = "some caption"
product_image.product = product_entry
product_image.original = image
product_image.original.save('my_product_filename.jpg', image) # <-----
product_image.save()
...
```

Body:
I am currently programatically importing products into my product catalog, however, I am having difficulty uploading images for each product. Here's what my code looks like:

# frobshop/custom_utils/product_importer.py

from oscar.apps.catalogue.models import Product
...

for product in my_product_import_list:
    ...
    product_entry = Product()
    product_entry.title = my_product_title
    product_entry.product_class = my_product_class
    product_entry.category = my_category
    product_entry.primary_image = "product_images/my_product_filename.jpg"
    product_entry.save()

The details such as product title and product class are successfully saved when I check using the development server, however, I am unsure how to set an image for each product.

The entire product_images folder was initially located outside of my media directory, but since I wasn't getting any results, I copy pasted the entire folder of my images into the media directory but still with no results.  I am assuming that quite a number of steps are being skipped, and maybe there's a convention on how to arrange images in the media directory.  However, I am not sure where to find these steps and conventions.

Here's the portion of my settings.py file that deals with my installed apps, the media directory, and static files:

# frobshop/frobshop/settings.py

...

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',

    'django.contrib.sites',

    'django.contrib.messages',
    'django.contrib.staticfiles',

    'django.contrib.flatpages',

    'compressor',
    'widget_tweaks',
] + get_core_apps(['custom_apps.shipping', 'custom_apps.payment', 'custom_apps.checkout'])

...

STATIC_ROOT = 'static'
STATIC_URL = '/static/'
MEDIA_ROOT = 'media'
MEDIA_URL = '/media/'

For further clarity, here's my urls.py

from django.contrib import admin
from django.urls import path
from django.conf.urls import include, url
from oscar.app import application
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    url(r'^i18n/', include('django.conf.urls.i18n')),
    path('admin/', admin.site.urls),
    url(r'', application.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Body:
Not entirely sure how helpful this will be to anyone, but I was getting a SuspiciousFileOperation Exception when using @ruddra's answer here, even though I was using a tempfile within the media root...

File "/Users/user/Documents/project/venv/lib/python3.7/site-packages/django/core/files/utils.py", line 19, in validate_file_name
    "Detected path traversal attempt in '%s'" % name
django.core.exceptions.SuspiciousFileOperation: Detected path traversal attempt in '/Users/user/Documents/project/media/images/tmp6xem6hvs'

Fixed by first saving the image (got the idea from this SO answer), then saving the product image:

import tempfile
from django.core.files.images import ImageFile
...
lf = tempfile.NamedTemporaryFile(dir='media')
f = open('<full_path_to_project>/media/images/my_product_filename.jpg', 'rb')
lf.write(f.read())
image = ImageFile(lf)
product_image = ProductImage()
product_image.caption = "some caption"
product_image.product = product_entry
product_image.original = image
product_image.original.save('my_product_filename.jpg', image) # <-----
product_image.save()
...


问:
Count number of objects in JSON array on a URL in swift5
I have a JSON array at url = https://api.github.com/users/greenrobot/starred .

I want to count how many objects are there in that array using swift. I don't want data present, I just want count of it.

答:
I assume that you are using Alamofire for making a network request. In the code below we are just extracting the value object from Alamofire result. We convert the value to Array of dictionaries and then you can just get the count.</p>
```<code>AF.request("https://api.github.com/users/greenrobot/starred",method: .get).responseJSON { apiResponse in
        switch apiResponse.result{
        case .success(_):
            let dictionary = apiResponse.value as? [[String:Any]]
            print("dictionaryCount \(dictionary?.count ?? -1)")
        case .failure(_):
            print("error \(apiResponse.error?.underlyingError?.localizedDescription ?? "")")
        }
    }
</code>```

Body:
I assume that you are using Alamofire for making a network request. In the code below we are just extracting the value object from Alamofire result. We convert the value to Array of dictionaries and then you can just get the count.

AF.request("https://api.github.com/users/greenrobot/starred",method: .get).responseJSON { apiResponse in
        switch apiResponse.result{
        case .success(_):
            let dictionary = apiResponse.value as? [[String:Any]]
            print("dictionaryCount \(dictionary?.count ?? -1)")
        case .failure(_):
            print("error \(apiResponse.error?.underlyingError?.localizedDescription ?? "")")
        }
    }


问:
auto return types in C++ function vs specifying return type
In my work's codebase, I see the following

```<code>class custom {
  auto set_data_type(custom_type_t type_t) -> custom & {
    // set some stuff
    // return *this;
  }
}
</code>```

Why can't we simply just do

```<code>class custom {
  custom & set_data_type(custom_type_t type_t) {
    // set some stuff
    // return *this;
  }
}
</code>```

What is the point of using auto in this case when you already know the return type and already wrote it out in the ->... place?

It seems auto would only be beneficial if it is used with decltype(arg) and where arg may have varying return types?

答: I believe, "auto" should not be used at all. IMHO, this is ugly sibling of void*; it hides types from programmer, while it is better to know exactly what type is used; this makes one's programming style clumsy, confuses and invites bugs. While the only "reasonable" use of this is typename "shortening", it is actually ridiculous, because short type names don't need to replaced, and for long names there is another keyword. IMHO.</p>

Body:
In my work's codebase, I see the following

class custom {
  auto set_data_type(custom_type_t type_t) -> custom & {
    // set some stuff
    // return *this;
  }
}

Why can't we simply just do

class custom {
  custom & set_data_type(custom_type_t type_t) {
    // set some stuff
    // return *this;
  }
}

What is the point of using auto in this case when you already know the return type and already wrote it out in the ->... place?

It seems auto would only be beneficial if it is used with decltype(arg) and where arg may have varying return types?


问:
Why can the as operator be used with Nullable<T>?
According to the documentation of the as operator, as "is used to perform certain types of conversions between compatible reference types".  Since Nullable is actually a value type, I would expect as not to work with it.  However, this code compiles and runs:

```<code>object o = 7;
int i = o as int? ?? -1;
Console.WriteLine(i); // output: 7
</code>```

Is this correct behavior?  Is the documentation for as wrong?  Am I missing something?

答: You're applying the 'as' to Object, which is a reference type.  It could be null, in which case the CLR has special support for unboxing the reference 'null' to a nullable value type.  This special unboxing is not supported for any other value type, so, even though Nullable is a value type, it does have certain special privledges.</p>

Body:
According to the documentation of the as operator, as "is used to perform certain types of conversions between compatible reference types".  Since Nullable is actually a value type, I would expect as not to work with it.  However, this code compiles and runs:

object o = 7;
int i = o as int? ?? -1;
Console.WriteLine(i); // output: 7

Is this correct behavior?  Is the documentation for as wrong?  Am I missing something?


问:
How can I convert a csv file using the csv dart package that contains ä, ö, ü, (different charset than US-ASCII)?
I am trying to convert a csv file to List<List> using the dart package csv, but failed when the file contained characters such as ä or ö which are not part of US-ASCII. I looked into the documentation and didn't find any setting to change the character set. It only states that the converter follows the rules of rfc4180.

This converter follows the rules of rfc4180.

On their webpage they state:

Common usage of CSV is US-ASCII, but other character sets defined
by IANA for the "text" tree may be used in conjunction with the
"charset" parameter.

This is the error I am getting:

```<code>Error: FormatException: Missing extension byte (at offset 120)
at Object.throw_ [as throw] (http://localhost:55338/dart_sdk.js:5333:11)
at convert._Utf8Decoder.new.convertGeneral (http://localhost:55338/dart_sdk.js:49223:19)
at convert._Utf8Decoder.new.convertSingle (http://localhost:55338/dart_sdk.js:49195:19)
at Utf8Decoder.convert (http://localhost:55338/dart_sdk.js:49054:67)
at Utf8Codec.decode (http://localhost:55338/dart_sdk.js:48760:22)
at asset_bundle.PlatformAssetBundle.new.loadString (http://localhost:55338/packages/flutter/src/services/system_channels.dart.lib.js:2308:31)
at loadString.next (<anonymous>)
at http://localhost:55338/dart_sdk.js:39031:33
at _RootZone.runUnary (http://localhost:55338/dart_sdk.js:38888:58)
at _FutureListener.thenAwait.handleValue (http://localhost:55338/dart_sdk.js:33874:29)
at handleValueCallback (http://localhost:55338/dart_sdk.js:34434:49)
at Function._propagateToListeners (http://localhost:55338/dart_sdk.js:34472:17)
at _Future.new.[_completeWithValue] (http://localhost:55338/dart_sdk.js:34314:23)
at async._AsyncCallbackEntry.new.callback (http://localhost:55338/dart_sdk.js:34337:35)
at Object._microtaskLoop (http://localhost:55338/dart_sdk.js:39175:13)
at _startMicrotaskLoop (http://localhost:55338/dart_sdk.js:39181:13)
at http://localhost:55338/dart_sdk.js:34688:9
</code>```

This is the code

```<code>  Future<String> determineNewWord({String path}) async {
    final myData = await rootBundle.loadString(path);
    List<List<dynamic>> csvTable = CsvToListConverter().convert(myData);
    print(csvTable);
    String newWord = csvTable[Random().nextInt(csvTable.length)].first;
    return newWord.toUpperCase();
  }
</code>```

I can't find a place to change the parameter, does this dart package not support other character sets?

Thank You! :)

答:
Actually, there shouldn't be any problems.

Below is a simple example as proof.

bin/data.csv

German,English
fallen – fällen,to fall – to fell
Fuß – Füße,foot – feet
alt – älter – am ältesten,old – elder – eldest
voll – füllen,full – fill
lang – Länge,long – length
Laus – Läuse,louse – lice
```
<p><code>bin/test_csv.dart</code></p>
<pre class="lang-dart prettyprint-override"><code>import 'dart:io';

import 'package:fast_csv/fast_csv.dart' as _fast_csv;

void main(List<String> args) {
  final source = File('bin/data.csv').readAsStringSync();
  final data = _fast_csv.parse(source);
  print(data.join('\n'));
}

</code>```

Output:

```<code>[German, English]
[fallen – fällen, to fall – to fell]
[Fuß – Füße, foot – feet]
[alt – älter – am ältesten, old – elder – eldest]
[voll – füllen, full – fill]
[lang – Länge, long – length]
[Laus – Läuse, louse – lice]
</code>```

This is because there are no restrictions on character sets in CSV format.

Body:
I am trying to convert a csv file to List<List> using the dart package csv, but failed when the file contained characters such as ä or ö which are not part of US-ASCII. I looked into the documentation and didn't find any setting to change the character set. It only states that the converter follows the rules of rfc4180.

This converter follows the rules of rfc4180.

On their webpage they state:

Common usage of CSV is US-ASCII, but other character sets defined
by IANA for the "text" tree may be used in conjunction with the
"charset" parameter.

This is the error I am getting:

Error: FormatException: Missing extension byte (at offset 120)
at Object.throw_ [as throw] (http://localhost:55338/dart_sdk.js:5333:11)
at convert._Utf8Decoder.new.convertGeneral (http://localhost:55338/dart_sdk.js:49223:19)
at convert._Utf8Decoder.new.convertSingle (http://localhost:55338/dart_sdk.js:49195:19)
at Utf8Decoder.convert (http://localhost:55338/dart_sdk.js:49054:67)
at Utf8Codec.decode (http://localhost:55338/dart_sdk.js:48760:22)
at asset_bundle.PlatformAssetBundle.new.loadString (http://localhost:55338/packages/flutter/src/services/system_channels.dart.lib.js:2308:31)
at loadString.next (<anonymous>)
at http://localhost:55338/dart_sdk.js:39031:33
at _RootZone.runUnary (http://localhost:55338/dart_sdk.js:38888:58)
at _FutureListener.thenAwait.handleValue (http://localhost:55338/dart_sdk.js:33874:29)
at handleValueCallback (http://localhost:55338/dart_sdk.js:34434:49)
at Function._propagateToListeners (http://localhost:55338/dart_sdk.js:34472:17)
at _Future.new.[_completeWithValue] (http://localhost:55338/dart_sdk.js:34314:23)
at async._AsyncCallbackEntry.new.callback (http://localhost:55338/dart_sdk.js:34337:35)
at Object._microtaskLoop (http://localhost:55338/dart_sdk.js:39175:13)
at _startMicrotaskLoop (http://localhost:55338/dart_sdk.js:39181:13)
at http://localhost:55338/dart_sdk.js:34688:9

This is the code

  Future<String> determineNewWord({String path}) async {
    final myData = await rootBundle.loadString(path);
    List<List<dynamic>> csvTable = CsvToListConverter().convert(myData);
    print(csvTable);
    String newWord = csvTable[Random().nextInt(csvTable.length)].first;
    return newWord.toUpperCase();
  }

I can't find a place to change the parameter, does this dart package not support other character sets?

Thank You! :)

Body:
Actually, there shouldn't be any problems.

Below is a simple example as proof.

bin/data.csv

German,English
fallen – fällen,to fall – to fell
Fuß – Füße,foot – feet
alt – älter – am ältesten,old – elder – eldest
voll – füllen,full – fill
lang – Länge,long – length
Laus – Läuse,louse – lice

bin/test_csv.dart

import 'dart:io';

import 'package:fast_csv/fast_csv.dart' as _fast_csv;

void main(List<String> args) {
  final source = File('bin/data.csv').readAsStringSync();
  final data = _fast_csv.parse(source);
  print(data.join('\n'));
}

Output:

[German, English]
[fallen – fällen, to fall – to fell]
[Fuß – Füße, foot – feet]
[alt – älter – am ältesten, old – elder – eldest]
[voll – füllen, full – fill]
[lang – Länge, long – length]
[Laus – Läuse, louse – lice]

This is because there are no restrictions on character sets in CSV format.


问:
JavaScript - How to get holiday list of a specific year using Google Calendar API?
I am using Google API v3 for retrieving the holiday lists, here is how I use the API: https://www.googleapis.com/calendar/v3/calendars/en.usa%23holiday%40group.v.calendar.google.com/events?key=myAPIKey

It returns a list of holidays of its own way (some of them are 2021 and some of them are 2022), but I want to get a list of holidays of my own specific year. Like I pass the year 2021, then it will return all the holidays of 2021, similarly, if I pass 2022, then it will return 2022. But I have no idea how to pass a year parameter, or I have no idea whether Google Calendar allows passing such parameter for holidays.

Can anyone please help me?

答:
According to the Google API Docs https://developers.google.com/calendar/api/v3/reference

There is a timeMax and timeMin url param that accepts a date/time range:

Must be an RFC3339 timestamp with mandatory time zone offset, for example, 2011-06-03T10:00:00-07:00, 2011-06-03T10:00:00Z. Milliseconds may be provided but are ignored. If timeMin is set, timeMax must be greater than timeMin.

https://www.googleapis.com/calendar/v3/calendars/primary/events?q=timeMax=2021-06-03T10%3A00%3A00-07%3A00&timeMin=2011-06-03T10%3A00%3A00-07%3A00

Note: The : are url encoded to: %3A


问:
number of element in Redis namespace
I have redis like this

is there any way to count the number of elements in each namespace with python?
I found HGETALL and DBSIZE but didn't work for me.

答:
You can use command "scan db_index" like "scan 0" or command "info keyspace" for all database indexes and get key count, average ttl (expiration time) and expires keys. You can also use two commands "select db_index" which db_index is 0,1,2,...,15 and the other command "dbsize" to get database key count.
The command "info" show a lot info about system specifications and redis.</p>

Title: number of element in Redis namespace


问:
Assigning a string value if input value falls within a specific range in Laravel 8
I compare an input value to multiple range of values to determine the string value for another variable.  The below code works, but I am wondering if there is a more elegant solution?</p>
```<code>...
if ($totalPoints >= 0 && $totalPoints <= 249) {
    $carClass = 'CC01';
} elseif ($totalPoints >= 250 && $totalPoints <= 299) {
    $carClass = 'CC02';
} elseif ($totalPoints >= 300 && $totalPoints <= 349) {
    $carClass = 'CC03';
} elseif ($totalPoints >= 350 && $totalPoints <= 399) {
    $carClass = 'CC04';
} elseif ($totalPoints >= 400 && $totalPoints <= 449) {
    $carClass = 'CC05';
} elseif ($totalPoints >= 450 && $totalPoints <= 499) {
    $carClass = 'CC06';
} elseif ($totalPoints >= 500 && $totalPoints <= 549) {
    $carClass = 'CC07';
} elseif ($totalPoints >= 550 && $totalPoints <= 599) {
    $carClass = 'CC08';
} elseif ($totalPoints >= 600 && $totalPoints <= 649) {
    $carClass = 'CC09';
} elseif ($totalPoints >= 650 && $totalPoints <= 699) {
    $carClass = 'CC10';
} elseif ($totalPoints >= 700 && $totalPoints <= 749) {
    $carClass = 'CC11';
} elseif ($totalPoints >= 750 && $totalPoints <= 824) {
    $carClass = 'CC12';
} elseif ($totalPoints >= 825 && $totalPoints <= 899) {
    $carClass = 'CC13';
} elseif ($totalPoints >= 900 && $totalPoints <= 974) {
    $carClass = 'CC14';
} elseif ($totalPoints >= 975 && $totalPoints <= 1049) {
    $carClass = 'CC15';
} elseif ($totalPoints >= 1050 && $totalPoints <= 1149) {
    $carClass = 'CC16';
} elseif ($totalPoints >= 1150 && $totalPoints <= 1249) {
    $carClass = 'CC17';
} elseif ($totalPoints >= 1250) {
    $carClass = 'CC18';
}
...
</code>```

答:
Based on your code I think that the $carClass always has the format CCXX where XX is two digits number and starts from 0 to the ranges count.
So you can use the 2nd value for each range and add them to the array and get the index of the desired value after sorting the array

```<code>$totalPoints = 290;
// -1 to get CC01 for 0 value
$breaks = [-1, 249, 299, 349, 399, 449]; // add all the 2nd values
$breaks[] = $totalPoints;
asort($breaks);
$breaks = array_values($breaks);
$index = array_search($totalPoints, $breaks);
$carClass = 'CC' . str_pad($index, 2, '0', STR_PAD_LEFT);
echo $carClass; // CC02
</code>```

Body:
I compare an input value to multiple range of values to determine the string value for another variable.  The below code works, but I am wondering if there is a more elegant solution?

...
if ($totalPoints >= 0 && $totalPoints <= 249) {
    $carClass = 'CC01';
} elseif ($totalPoints >= 250 && $totalPoints <= 299) {
    $carClass = 'CC02';
} elseif ($totalPoints >= 300 && $totalPoints <= 349) {
    $carClass = 'CC03';
} elseif ($totalPoints >= 350 && $totalPoints <= 399) {
    $carClass = 'CC04';
} elseif ($totalPoints >= 400 && $totalPoints <= 449) {
    $carClass = 'CC05';
} elseif ($totalPoints >= 450 && $totalPoints <= 499) {
    $carClass = 'CC06';
} elseif ($totalPoints >= 500 && $totalPoints <= 549) {
    $carClass = 'CC07';
} elseif ($totalPoints >= 550 && $totalPoints <= 599) {
    $carClass = 'CC08';
} elseif ($totalPoints >= 600 && $totalPoints <= 649) {
    $carClass = 'CC09';
} elseif ($totalPoints >= 650 && $totalPoints <= 699) {
    $carClass = 'CC10';
} elseif ($totalPoints >= 700 && $totalPoints <= 749) {
    $carClass = 'CC11';
} elseif ($totalPoints >= 750 && $totalPoints <= 824) {
    $carClass = 'CC12';
} elseif ($totalPoints >= 825 && $totalPoints <= 899) {
    $carClass = 'CC13';
} elseif ($totalPoints >= 900 && $totalPoints <= 974) {
    $carClass = 'CC14';
} elseif ($totalPoints >= 975 && $totalPoints <= 1049) {
    $carClass = 'CC15';
} elseif ($totalPoints >= 1050 && $totalPoints <= 1149) {
    $carClass = 'CC16';
} elseif ($totalPoints >= 1150 && $totalPoints <= 1249) {
    $carClass = 'CC17';
} elseif ($totalPoints >= 1250) {
    $carClass = 'CC18';
}
...

Body:
Based on your code I think that the $carClass always has the format CCXX where XX is two digits number and starts from 0 to the ranges count.
So you can use the 2nd value for each range and add them to the array and get the index of the desired value after sorting the array

$totalPoints = 290;
// -1 to get CC01 for 0 value
$breaks = [-1, 249, 299, 349, 399, 449]; // add all the 2nd values
$breaks[] = $totalPoints;
asort($breaks);
$breaks = array_values($breaks);
$index = array_search($totalPoints, $breaks);
$carClass = 'CC' . str_pad($index, 2, '0', STR_PAD_LEFT);
echo $carClass; // CC02


问:
How to make fast recompile time of react application in visual studio code
For the past 3/4 days, my react app take more than 3 to 5 minute to compile. My device has 4GB Ram 128 GB SSD and a 500GB hard disk. My project is medium size and I use VS Code editor. All other apps working perfectly. Please help how to fix this issue.</p>

答:
The problem could relate to eslint configuration, if so, you could try to add on the .env file DISABLE_ESLINT_PLUGIN=true and see if there's a considerable change in the recompilation time.

You could try and switch a package manager, yarn is recommended for fast compilation time if you are not using it already.


问:
How to concatenate more sql queries to get one table?
I have 4 tables that I have used following queries to get data,

```<code>query1 : select * from userdetails1.UserTable;

Result1:
UserID  Username    Status
1         John      Active
2         Micheal   Active
3         Ann       Active
4         Shasha    Resigned
5         mike      Resigned

query2 : select * from userdetails2.AmountTable;

result2:
UserId  TotalAmount TotalAmountResetDate
1          -12         1/31/2022
2          345         1/31/2022
3          213         1/31/2022
4          0           1/31/2022
5          0           1/31/2022

query3:
select Username,TotalInvested from userdetails2.TotalInvestmentsTable group by Username;

result3:

Username    Totalnvested
John         45000
Micheal      45000
Ann          45000

query4:
select Username,TotalExpenses from userdetails2.TotalExpensesTable group by Username;

Username    TotalExpenses
John           2543
Micheal        2345
Ann            3290
</code>```

Now I need to get another table by combining all these queries as follows. How should I get that by concatenating all these queries?

```<code>UserId  Username    TotalAmountResetDate    TotalAmount Totalnvested    TotalExpenses   TotalBalance
1        John              1/31/2022               -12       45000            2543          42445
2        Micheal           1/31/2022               345       45000            2345          43000
3        Ann               1/31/2022               213       45000            3290          41923
4        Shasha            1/31/2022               0         0                 0            0
5        mike              1/31/2022               0         0                 0            0
</code>```

Here TotalBalance column need to get from TotalBalance=TotalAmount+Totalnvested -TotalExpenses.Is this possible to get using one query?

Update:

If the total expenses and total investments are more than one value we need to get sum of each user to the total investements. Then how we can get that one?

Example:

```<code>Username    Totalnvested
    John         45000
    Micheal      45000
    Ann          45000
    John         21000
    Micheal       5000

Username    TotalExpenses
John           2543
Micheal        2345
Ann            3290
Ann            2345
John            5478
</code>```

答:
Have you tried Joins command? Inner join, Full join?

https://www.w3schools.com/sql/sql_join.asp

Body:
I have 4 tables that I have used following queries to get data,

query1 : select * from userdetails1.UserTable;

Result1:
UserID  Username    Status
1         John      Active
2         Micheal   Active
3         Ann       Active
4         Shasha    Resigned
5         mike      Resigned

query2 : select * from userdetails2.AmountTable;

result2:
UserId  TotalAmount TotalAmountResetDate
1          -12         1/31/2022
2          345         1/31/2022
3          213         1/31/2022
4          0           1/31/2022
5          0           1/31/2022

query3:
select Username,TotalInvested from userdetails2.TotalInvestmentsTable group by Username;

result3:

Username    Totalnvested
John         45000
Micheal      45000
Ann          45000

query4:
select Username,TotalExpenses from userdetails2.TotalExpensesTable group by Username;

Username    TotalExpenses
John           2543
Micheal        2345
Ann            3290

Now I need to get another table by combining all these queries as follows. How should I get that by concatenating all these queries?

UserId  Username    TotalAmountResetDate    TotalAmount Totalnvested    TotalExpenses   TotalBalance
1        John              1/31/2022               -12       45000            2543          42445
2        Micheal           1/31/2022               345       45000            2345          43000
3        Ann               1/31/2022               213       45000            3290          41923
4        Shasha            1/31/2022               0         0                 0            0
5        mike              1/31/2022               0         0                 0            0

Here TotalBalance column need to get from TotalBalance=TotalAmount+Totalnvested -TotalExpenses.Is this possible to get using one query?

Update:

If the total expenses and total investments are more than one value we need to get sum of each user to the total investements. Then how we can get that one?

Example:

Username    Totalnvested
    John         45000
    Micheal      45000
    Ann          45000
    John         21000
    Micheal       5000

Username    TotalExpenses
John           2543
Micheal        2345
Ann            3290
Ann            2345
John            5478


问:
How do I get tailwinds active breakpoint in JavaScript?
I am building tailwind with config file and including it in a react project.

I would like to get the active breakpoint value in javascript/React. How can I achieve the same.?

al

sm

md

lg

xl

```

The above shows the active breakpoint. but how do i get the same in js without including any of the above markup.?

答:
Here is a little hook for those using TypeScript 4.5+. It's based on the useMediaQuery hook from the react-responsive package. Modify it as you please!

```<code>import { useMediaQuery } from 'react-responsive';
import { theme } from '../../tailwind.config'; // Your tailwind config

const breakpoints = theme.screens;

type BreakpointKey = keyof typeof breakpoints;

export function useBreakpoint<K extends BreakpointKey>(breakpointKey: K) {
  const bool = useMediaQuery({
    query: `(min-width: ${breakpoints[breakpointKey]})`,
  });
  const capitalizedKey = breakpointKey[0].toUpperCase() + breakpointKey.substring(1);
  type Key = `is${Capitalize<K>}`;
  return {
    [`is${capitalizedKey}`]: bool,
  } as Record<Key, boolean>;
}
</code>```

Inside your component, use it like this

```<code>const { isSm } = useBreakpoint('sm');
const { isMd } = useBreakpoint('md');
const { isLg } = useBreakpoint('lg');
return (
      <div>
        {isSm && (
          {/* Visible for sm: (min-width: 640px) */}
          <div>Content</div>
        )}

        {isMd && (
          {/* Visible for md: (min-width: 768px) */}
          <div>Content</div>
        )}
      </div>
  );
</code>```

Body:
I am building tailwind with config file and including it in a react project.

I would like to get the active breakpoint value in javascript/React. How can I achieve the same.?

al

sm

md

lg

xl

The above shows the active breakpoint. but how do i get the same in js without including any of the above markup.?

Body:
Here is a little hook for those using TypeScript 4.5+. It's based on the useMediaQuery hook from the react-responsive package. Modify it as you please!

import { useMediaQuery } from 'react-responsive';
import { theme } from '../../tailwind.config'; // Your tailwind config

const breakpoints = theme.screens;

type BreakpointKey = keyof typeof breakpoints;

export function useBreakpoint<K extends BreakpointKey>(breakpointKey: K) {
  const bool = useMediaQuery({
    query: `(min-width: ${breakpoints[breakpointKey]})`,
  });
  const capitalizedKey = breakpointKey[0].toUpperCase() + breakpointKey.substring(1);
  type Key = `is${Capitalize<K>}`;
  return {
    [`is${capitalizedKey}`]: bool,
  } as Record<Key, boolean>;
}

Inside your component, use it like this

const { isSm } = useBreakpoint('sm');
const { isMd } = useBreakpoint('md');
const { isLg } = useBreakpoint('lg');
return (
      <div>
        {isSm && (
          {/* Visible for sm: (min-width: 640px) */}
          <div>Content</div>
        )}

        {isMd && (
          {/* Visible for md: (min-width: 768px) */}
          <div>Content</div>
        )}
      </div>
  );


问:
Google Location distance calculation using python dataframes
I am trying to tease out the dates that I was in a certain area (within a mile or so) using Google Location data and Python Pandas Dataframe.

First convert to latitude from latitudeE7:

```<code>with open(Takeout_google_location_history) as f:
data = json.loads(f.read())

df = json_normalize(data['locations'])
df['latitudeE7'] = df['latitudeE7'].div(10000000.0)
df['longitudeE7'] = df['longitudeE7'].div(10000000.0)
df.head()
</code>```

Then calculate the distance:

```<code>import haversine as hs
from haversine import Unit
loc1 = (31.393300,-99.070050)
df['diff'] = hs.haversine(loc1,(df['latitudeE7'],df['longitudeE7']),unit=Unit.MILES)
df.head()
</code>```

And getting this error:

```<code>~\Anaconda2\envs\notebook\lib\site-packages\haversine\haversine.py in
haversine(point1, point2, unit)
     92     lat1 = radians(lat1)
     93     lng1 = radians(lng1)
---> 94     lat2 = radians(lat2)
     95     lng2 = radians(lng2)
     96

~\Anaconda2\envs\notebook\lib\site-packages\pandas\core\series.py in             wrapper(self)
    183         if len(self) == 1:
    184             return converter(self.iloc[0])
--> 185         raise TypeError(f"cannot convert the series to {converter}")
    186
    187     wrapper.__name__ = f"__{converter.__name__}__"

TypeError: cannot convert the series to <class 'float'>
</code>```

I am not sure what to do with the data to make it a float.

I have tried:

```<code>df['latitudeE7'] = df['latitudeE7'].div(10000000.0).astype(float)
</code>```

As well as using a hand written distance:

```<code>import math
def distance(origin, destination):

  lat1, lon1 = origin
  lat2, lon2 = destination
  radius = 6371  # km

  dlat = math.radians(float(lat2) - lat1)
  dlon = math.radians(float(lon2) - lon1)
  a = (math.sin(dlat / 2) * math.sin(dlat / 2) +
     math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) *
     math.sin(dlon / 2) * math.sin(dlon / 2))
  c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
  d = radius * c

  return d
</code>```

Still getting the same error:

```<code>~\AppData\Local\Temp/ipykernel_22916/3664391511.py in distance(origin, destination)
     26     radius = 6371  # km
     27
---> 28     dlat = math.radians(float(lat2) - lat1)
     29     dlon = math.radians(float(lon2) - lon1)
     30     a = (math.sin(dlat / 2) * math.sin(dlat / 2) +

~\Anaconda2\envs\notebook\lib\site-packages\pandas\core\series.py in wrapper(self)
    183         if len(self) == 1:
    184             return converter(self.iloc[0])
--> 185         raise TypeError(f"cannot convert the series to {converter}")
    186
    187     wrapper.__name__ = f"__{converter.__name__}__"

TypeError: cannot convert the series to <class 'float'>
</code>```

答:
You cannot directly pass pd.Series to haversine function.

Code:

from haversine import haversine, Unit
import pandas as pd

loc1 = (31.393300, -99.070050)

# Sample dataframe
df = pd.DataFrame({'latitudeE7': [0, 0], 'longitudeE7': [0, 0]})

# Calculation
# df['diff'] = haversine(loc1, (df['latitudeE7'], df['longitudeE7']), unit=Unit.MILES) # This doesn't work
df['diff'] = df.apply(lambda row: haversine(loc1, (row['latitudeE7'], row['longitudeE7']), unit=Unit.MILES), axis=1)
```
<h2>Output:</h2>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: center;">latitudeE7</th>
<th style="text-align: center;">longitudeE7</th>
<th style="text-align: center;">diff</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: center;">0</td>
<td style="text-align: center;">0</td>
<td style="text-align: center;">6752.74</td>
</tr>
<tr>
<td style="text-align: center;">0</td>
<td style="text-align: center;">0</td>
<td style="text-align: center;">6752.74</td>
</tr>
</tbody>
</table>
</div><h2>Reference:</h2>
<p>The issue you have seems related to the following post: understanding math errors in pandas dataframes</p>
<hr />
<h1>[EDIT]</h1>
<p>If the number of rows is large, <code>haversin_vector</code> will be the proper method in terms of speed.</p>
<h2>Code</h2>
<h3># Preparation:</h3>
<pre class="lang-py prettyprint-override"><code>from haversine import haversine, haversine_vector, Unit
import pandas as pd
import numpy as np

loc1 = (31.393300, -99.070050)

# Sample dataframe
n = 1000000
df = pd.DataFrame({'latitudeE7': np.random.rand(n) * 180 - 90, 'longitudeE7': np.random.rand(n) * 360 - 180})
</code>```

# Speed test 1 (Use haversine)

df['diff'] = df.apply(lambda row: haversine(loc1, (row['latitudeE7'], row['longitudeE7']), unit=Unit.MILES), axis=1)
```
```9.9 s ± 172 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
```
<h3># Speed test 2 (Use <code>haversine_vector</code>)</h3>
<pre class="lang-py prettyprint-override"><code>df['diff'] = haversine_vector(loc1, df, unit=Unit.MILES, comb=True)
</code>```
```<code>105 ms ± 1.1 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
</code>```

Reference:

haversine_vector: document

haversine_vector: implementation

Body:
I am trying to tease out the dates that I was in a certain area (within a mile or so) using Google Location data and Python Pandas Dataframe.

First convert to latitude from latitudeE7:

with open(Takeout_google_location_history) as f:
data = json.loads(f.read())

df = json_normalize(data['locations'])
df['latitudeE7'] = df['latitudeE7'].div(10000000.0)
df['longitudeE7'] = df['longitudeE7'].div(10000000.0)
df.head()

Then calculate the distance:

import haversine as hs
from haversine import Unit
loc1 = (31.393300,-99.070050)
df['diff'] = hs.haversine(loc1,(df['latitudeE7'],df['longitudeE7']),unit=Unit.MILES)
df.head()

And getting this error:

~\Anaconda2\envs\notebook\lib\site-packages\haversine\haversine.py in
haversine(point1, point2, unit)
     92     lat1 = radians(lat1)
     93     lng1 = radians(lng1)
---> 94     lat2 = radians(lat2)
     95     lng2 = radians(lng2)
     96

~\Anaconda2\envs\notebook\lib\site-packages\pandas\core\series.py in             wrapper(self)
    183         if len(self) == 1:
    184             return converter(self.iloc[0])
--> 185         raise TypeError(f"cannot convert the series to {converter}")
    186
    187     wrapper.__name__ = f"__{converter.__name__}__"

TypeError: cannot convert the series to <class 'float'>

I am not sure what to do with the data to make it a float.

I have tried:

df['latitudeE7'] = df['latitudeE7'].div(10000000.0).astype(float)

As well as using a hand written distance:

import math
def distance(origin, destination):

  lat1, lon1 = origin
  lat2, lon2 = destination
  radius = 6371  # km

  dlat = math.radians(float(lat2) - lat1)
  dlon = math.radians(float(lon2) - lon1)
  a = (math.sin(dlat / 2) * math.sin(dlat / 2) +
     math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) *
     math.sin(dlon / 2) * math.sin(dlon / 2))
  c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
  d = radius * c

  return d

Still getting the same error:

~\AppData\Local\Temp/ipykernel_22916/3664391511.py in distance(origin, destination)
     26     radius = 6371  # km
     27
---> 28     dlat = math.radians(float(lat2) - lat1)
     29     dlon = math.radians(float(lon2) - lon1)
     30     a = (math.sin(dlat / 2) * math.sin(dlat / 2) +

~\Anaconda2\envs\notebook\lib\site-packages\pandas\core\series.py in wrapper(self)
    183         if len(self) == 1:
    184             return converter(self.iloc[0])
--> 185         raise TypeError(f"cannot convert the series to {converter}")
    186
    187     wrapper.__name__ = f"__{converter.__name__}__"

TypeError: cannot convert the series to <class 'float'>

Body:
You cannot directly pass pd.Series to haversine function.

Code:

from haversine import haversine, Unit
import pandas as pd

loc1 = (31.393300, -99.070050)

# Sample dataframe
df = pd.DataFrame({'latitudeE7': [0, 0], 'longitudeE7': [0, 0]})

# Calculation
# df['diff'] = haversine(loc1, (df['latitudeE7'], df['longitudeE7']), unit=Unit.MILES) # This doesn't work
df['diff'] = df.apply(lambda row: haversine(loc1, (row['latitudeE7'], row['longitudeE7']), unit=Unit.MILES), axis=1)

Output:

latitudeE7
longitudeE7
diff

0
0
6752.74

0
0
6752.74

Reference:

The issue you have seems related to the following post: understanding math errors in pandas dataframes

[EDIT]

If the number of rows is large, haversin_vector will be the proper method in terms of speed.

Code

# Preparation:

from haversine import haversine, haversine_vector, Unit
import pandas as pd
import numpy as np

loc1 = (31.393300, -99.070050)

# Sample dataframe
n = 1000000
df = pd.DataFrame({'latitudeE7': np.random.rand(n) * 180 - 90, 'longitudeE7': np.random.rand(n) * 360 - 180})

# Speed test 1 (Use haversine)

df['diff'] = df.apply(lambda row: haversine(loc1, (row['latitudeE7'], row['longitudeE7']), unit=Unit.MILES), axis=1)

9.9 s ± 172 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

# Speed test 2 (Use haversine_vector)

df['diff'] = haversine_vector(loc1, df, unit=Unit.MILES, comb=True)

105 ms ± 1.1 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Reference:

haversine_vector: document

haversine_vector: implementation


问:
Issue laying out components with React and Flexbox
Here is a puzzling problem I am facing with the layout of some components in a web app.

First of all here is the source code MyCompo.js:

```<code>import React from "react";
import tblClp from './images/WoodSquare.jpg';
import dwnArwClp from './images/DownArrow.png';
import upArwClp from './images/UpArrow.png';
import './MyCompo.css';

class MyCompo extends React.Component {
  render() {
    const elements = [...Array(3).keys()]
    const items = []

    for (const [index, value] of elements.entries()) {
      items.push(<SquareUnit index={index}/>)
    }

    return (
      <div>
        {items}
      </div>
    )
  }
}

class SquareUnit extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <React.Fragment>
        <div id={this.props.index}>
                    <div><img src={tblClp} width='130' height='109'/>
            <div className="overlay down">
                <img src={dwnArwClp} width='40' height='40'/>
                </div>
            <div className="overlay up">
                <img src={upArwClp} width='40' height='40'/>
              </div>
                    </div>
        </div>
      </React.Fragment>
    )
  }
}

export default MyCompo;
</code>```

And here is the style sheet MyCompo.css:

```<code>body {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

.overlay {
    position: relative;
    height: 100%;
    width: 100%;
    opacity: 0.3;
    transition: .3s ease;
    background-color: transparent;
    bottom: 0;
    right: 0;
}

.down {
    top: -24%;
    left: 3%;
}

.up {
    top: -76%;
    left: 65%;
}

.container {
    position: relative;
    width: 100%;
    max-width: 400px;
}
</code>```

I run my app for development using this command in the terminal:

```<code>$ npm start
</code>```

And this is what I see in the browser after adjusting the .down {...} and .up {...} blocks inside MyCompo.css and saving the file.

As one can see MyCompo is made of three wooden square blocks, each one having two arrows (up and down) overlayed on top of it.

The above screenshot is what I get as well as what I expect.

But here comes the problem and my question:

When I refresh the browser window, the display changes to the following:

which is no longer what I expect.

What is wrong in my code MyCompo.js or MyCompo.css for this to happen?

答:
The problem is now solved, below is how I did.

First of all here is the new source code MyCompo.js:

```<code>    import React from "react";
    import dwnArwClp from './images/DownArrow.png';
    import upArwClp from './images/UpArrow.png';
    import './MyCompo.css';

    class MyCompo extends React.Component {
      render() {
        const elements = [...Array(3).keys()]

        const items = []

        for (const [index, value] of elements.entries()) {
          items.push(<SquareUnit index={index}/>)
        }

        return (
          <div>
            {items}
          </div>
        )
      }
    }

    class SquareUnit extends React.Component {
      constructor(props) {
        super(props);
      }

      render() {
        return (
          <React.Fragment>
            <div id={this.props.index} className='tblBlk'>
                        <div className='tblCell'>
                <div className="overlay down">
                    <img src={dwnArwClp} width='40' height='40'/>
                  </div>
                <div className="overlay up">
                    <img src={upArwClp} width='40' height='40'/>
                  </div>
                        </div>
            </div>
          </React.Fragment>
        )
      }
    }

    export default MyCompo;
</code>```

And here is the new style sheet MyCompo.css:

```<code>    body {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
    }

    .sqBlk {
        padding-top: 11px;
        padding-bottom: 11px;
    }

    .sqCell {
        background-image: url("./images/WoodSquare.jpg");
        width: 130px;
        height: 109px;
    }

    .overlay {
        position: relative;
        height: 100%;
        width: 100%;
        opacity: 0.4;
        transition: .3s ease;
        background-color: transparent;
        bottom: 0;
        right: 0;
    }

    .down {
        top: 60%;
        left: 4%;
    }

    .up {
        top: -96%;
        left: 65%;
    }
</code>```

Body:
Here is a puzzling problem I am facing with the layout of some components in a web app.

First of all here is the source code MyCompo.js:

import React from "react";
import tblClp from './images/WoodSquare.jpg';
import dwnArwClp from './images/DownArrow.png';
import upArwClp from './images/UpArrow.png';
import './MyCompo.css';

class MyCompo extends React.Component {
  render() {
    const elements = [...Array(3).keys()]
    const items = []

    for (const [index, value] of elements.entries()) {
      items.push(<SquareUnit index={index}/>)
    }

    return (

        {items}

    )
  }
}

class SquareUnit extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <React.Fragment>

      </React.Fragment>
    )
  }
}

export default MyCompo;

And here is the style sheet MyCompo.css:

body {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

.overlay {
    position: relative;
    height: 100%;
    width: 100%;
    opacity: 0.3;
    transition: .3s ease;
    background-color: transparent;
    bottom: 0;
    right: 0;
}

.down {
    top: -24%;
    left: 3%;
}

.up {
    top: -76%;
    left: 65%;
}

.container {
    position: relative;
    width: 100%;
    max-width: 400px;
}

I run my app for development using this command in the terminal:

$ npm start

And this is what I see in the browser after adjusting the .down {...} and .up {...} blocks inside MyCompo.css and saving the file.

As one can see MyCompo is made of three wooden square blocks, each one having two arrows (up and down) overlayed on top of it.

The above screenshot is what I get as well as what I expect.

But here comes the problem and my question:

When I refresh the browser window, the display changes to the following:

which is no longer what I expect.

What is wrong in my code MyCompo.js or MyCompo.css for this to happen?

Body:
The problem is now solved, below is how I did.

First of all here is the new source code MyCompo.js:

    import React from "react";
    import dwnArwClp from './images/DownArrow.png';
    import upArwClp from './images/UpArrow.png';
    import './MyCompo.css';

    class MyCompo extends React.Component {
      render() {
        const elements = [...Array(3).keys()]

        const items = []

        for (const [index, value] of elements.entries()) {
          items.push(<SquareUnit index={index}/>)
        }

        return (
          <div>
            {items}
          </div>
        )
      }
    }

    class SquareUnit extends React.Component {
      constructor(props) {
        super(props);
      }

      render() {
        return (
          <React.Fragment>
            <div id={this.props.index} className='tblBlk'>
                        <div className='tblCell'>
                <div className="overlay down">
                    <img src={dwnArwClp} width='40' height='40'/>
                  </div>
                <div className="overlay up">
                    <img src={upArwClp} width='40' height='40'/>
                  </div>
                        </div>
            </div>
          </React.Fragment>
        )
      }
    }

    export default MyCompo;

And here is the new style sheet MyCompo.css:

    body {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
    }

    .sqBlk {
        padding-top: 11px;
        padding-bottom: 11px;
    }

    .sqCell {
        background-image: url("./images/WoodSquare.jpg");
        width: 130px;
        height: 109px;
    }

    .overlay {
        position: relative;
        height: 100%;
        width: 100%;
        opacity: 0.4;
        transition: .3s ease;
        background-color: transparent;
        bottom: 0;
        right: 0;
    }

    .down {
        top: 60%;
        left: 4%;
    }

    .up {
        top: -96%;
        left: 65%;
    }


问:
Some beginner Objective-C/iPhone questions
I'm just starting out (reading up a lot for the past couple of days). Here's some questions that I have stacked up, hopefully someone can answer them.

1. the (self != nil) check in initializer code. Why do it? To prevent accidental access to some "run-only-once" code that's wrapped up in there? Where from could this accidental access come from? Doing such checks suggest that I don't have control over what's going on.

```
- (id)init {
    self = [super init]
    if (self != nil) {
    // Code..
    }
    return self;
}
```

2. How is it that you don't have to free up anything that static methods return? (or this is the idea I've got)

3. How is str = @"Hi there!" different from

```str = [[NSString alloc] initWithString:@"Hi there!"];```

As I understand, you have to release str in aquired with second method, but not with first? If so, when does the first one get released? Which one is preferable (not minding the typing length)?

4. What is autorelease, if iphone has no garbage collection? I've noticed something called "an autorelease pool" being created in main.m. Is [myObject autorelease]; a way of adding myObject to the nearest wrapping "autorelease pool", which will release it? Basically, some magic to avoid releasing it yourself? Why use it?

Well, thats it for now. Thanks for any answers!

答:
There is a school of thought that in most cases, allocating the self pointer is something that the system should do, and not the programmer.

Also, many people prefer to keep the main line of program flow as un-indented as possible. In which case the initialisation code could be re-written as:

```<code>- (id)init {
    if (![super init]) {
        return nil; // There is a problem so bail early.
    }
    // Initialisation code here.
    return self
}
</code>```

Will Shipley explains this much better than I do.

OwnerDisplayName: Karolis

ContentLicense: CC BY-SA 2.5

Body:
I'm just starting out (reading up a lot for the past couple of days). Here's some questions that I have stacked up, hopefully someone can answer them.

1. the (self != nil) check in initializer code. Why do it? To prevent accidental access to some "run-only-once" code that's wrapped up in there? Where from could this accidental access come from? Doing such checks suggest that I don't have control over what's going on.

- (id)init {
    self = [super init]
    if (self != nil) {
    // Code..
    }
    return self;
}

2. How is it that you don't have to free up anything that static methods return? (or this is the idea I've got)

3. How is str = @"Hi there!" different from

str = [[NSString alloc] initWithString:@"Hi there!"];

As I understand, you have to release str in aquired with second method, but not with first? If so, when does the first one get released? Which one is preferable (not minding the typing length)?

4. What is autorelease, if iphone has no garbage collection? I've noticed something called "an autorelease pool" being created in main.m. Is [myObject autorelease]; a way of adding myObject to the nearest wrapping "autorelease pool", which will release it? Basically, some magic to avoid releasing it yourself? Why use it?

Well, thats it for now. Thanks for any answers!

Body:
There is a school of thought that in most cases, allocating the self pointer is something that the system should do, and not the programmer.

Also, many people prefer to keep the main line of program flow as un-indented as possible. In which case the initialisation code could be re-written as:

- (id)init {
    if (![super init]) {
        return nil; // There is a problem so bail early.
    }
    // Initialisation code here.
    return self
}

Will Shipley explains this much better than I do.

OwnerDisplayName: Abizern


问:
how to add my own templates to eclipse in play! framework editor
I've noticed that the play plugin for eclipse adds a play editor,
along with several useful templates
I'd like to add my own ones, but I couldn't find the way to do it
I go to window, preferences, web, html files, templates and I can add
templates to eclipse html editor, but I couldn't find a similar option
for play editor </p>

答:
I had a lok at the source, it seems like the template editor tags are defined here

https://github.com/playframework/playclipse/blob/master/source/src/org/playframework/playclipse/editors/html/HTMLEditor.java

looks like there's no support for creating your own templates thru eclipse...


问:
Hide the content based on Children class
I need one help with the code, I have two HTML div blocks with the same class name and there is one extra h2 tag with different class present in one div block. I want to hide if h2 class name is not present in that div and show if the h2 class name is present. Please find the below mentioned code that I have created.

-- First block Div --

```<code><div class="course-content">
    <h2 class="accesshide"></h2>
    <ul class="topics">
        <li class="data-list">Content not to Display</li>
    </ul>
    <div class="row">
        <p>Content to Display</p>
    </div>
</div>
</code>```

-- Second block Div --

```<code><div class="course-content">
    <ul class="topics">
        <li class="data-list">Content not to Display</li>
    </ul>
    <div class="single-section">
        <p>Content to Display</p>
    </div>
</div>
</code>```

-- jQuery Code --

$(document).ready(function () {
    if ($(".course-content").find(".accesshide")) {
        $(".course-content").find(".topics").show();
    } else if ($(".course-content").find(".single-section")) {
        $(".course-content").find(".topics").hide();
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="course-content">
        <h2 class="accesshide"></h2>
        <ul class="topics">
            <li class="data-list">Content not to Display</li>
        </ul>
        <div class="row">
            <p>Content to Display (this statement is inaccurate)</p>
        </div>
    </div>

    <div class="course-content">
        <ul class="topics">
            <li class="data-list">Content not to Display (this statement is inaccurate)</li>
        </ul>
        <div class="single-section">
            <p>Content to Display</p>
        </div>
    </div></code>```

答:
This is trivial using a CSS child selector (>).  Just find the collection of elements that are an accesshide child of a course-content and hide the topics child of their parents.

You could do something similar with a descendant selector ( ), but since you know it's a child for this case, the child selector is perhaps more accurate.

MDN's Child Combinator docs.

$(document).ready(function () {
    $('.course-content>.accesshide').parent().find('.topics').hide();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="course-content">
        <h2 class="accesshide"></h2>
        <ul class="topics">
            <li class="data-list">Content not to Display</li>
        </ul>
        <div class="row">
            <p>Content to Display</p>
        </div>
    </div>

    <div class="course-content">
        <ul class="topics">
            <li class="data-list">Content not to Display (this should actually be shown - there's no h2 in the parent div)</li>
        </ul>
        <div class="single-section">
            <p>Content to Display</p>
        </div>
    </div></code>```

Body:
I need one help with the code, I have two HTML div blocks with the same class name and there is one extra h2 tag with different class present in one div block. I want to hide if h2 class name is not present in that div and show if the h2 class name is present. Please find the below mentioned code that I have created.

-- First block Div --

Content not to Display

Content to Display

-- Second block Div --

Content not to Display

Content to Display

-- jQuery Code --

$(document).ready(function () {
    if ($(".course-content").find(".accesshide")) {
        $(".course-content").find(".topics").show();
    } else if ($(".course-content").find(".single-section")) {
        $(".course-content").find(".topics").hide();
    }
});

Content not to Display

Content to Display (this statement is inaccurate)

Content not to Display (this statement is inaccurate)

Content to Display

Body:
This is trivial using a CSS child selector (>).  Just find the collection of elements that are an accesshide child of a course-content and hide the topics child of their parents.

You could do something similar with a descendant selector ( ), but since you know it's a child for this case, the child selector is perhaps more accurate.

MDN's Child Combinator docs.

$(document).ready(function () {
    $('.course-content>.accesshide').parent().find('.topics').hide();
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="course-content">
        <h2 class="accesshide"></h2>
        <ul class="topics">
            <li class="data-list">Content not to Display</li>
        </ul>
        <div class="row">
            <p>Content to Display</p>
        </div>
    </div>

    <div class="course-content">
        <ul class="topics">
            <li class="data-list">Content not to Display (this should actually be shown - there's no h2 in the parent div)</li>
        </ul>
        <div class="single-section">
            <p>Content to Display</p>
        </div>
    </div>


答:
This can be a way:</p>
```<code>$totalPoints = 399;

$rangeArray = [
    [0, 249, 'CC01'],
    [250, 299, 'CC02'],
    [300, 349, 'CC03'],
    [350, 399, 'CC04'],
    /* .... More range */
    [12520, null, 'CC18']
];

foreach($rangeArray as $range){
    if( ($totalPoints >= $range[0]) && ($range[1] ? ($totalPoints <= $range[1]) : true) ){
        $carClass = $range[2];
        break;
    }
}
echo $carClass;// CC04
</code>```

Title: Assigning a string value if input value falls within a specific range in Laravel 8

Body:
This can be a way:

$totalPoints = 399;

$rangeArray = [
    [0, 249, 'CC01'],
    [250, 299, 'CC02'],
    [300, 349, 'CC03'],
    [350, 399, 'CC04'],
    /* .... More range */
    [12520, null, 'CC18']
];

foreach($rangeArray as $range){
    if( ($totalPoints >= $range[0]) && ($range[1] ? ($totalPoints <= $range[1]) : true) ){
        $carClass = $range[2];
        break;
    }
}
echo $carClass;// CC04


问:
How to use setState without using onPressed
I am new to flutter and i want to setState  a variable that will use to display an on and off icon. onPressed cannot be used because the input switch is a string.

```<code>void _toggleIcon() {
  setState(() {
      if (switch.contains('on')) {
        _iconState = true;
      } else if (switch.contains('off')) {
        _iconState = false;
      }
  });
}
</code>```

I know that i can use the void function above on IconButton on onPressed using this code:

```<code>Container(
          padding: const EdgeInsets.all(0),
          child: IconButton(
            padding: const EdgeInsets.all(0),
            alignment: Alignment.centerRight,
            icon: (_iconState
                ? const Icon(Icons.star)
                : const Icon(Icons.star_border)),
            color: Colors.red[500],
            onPressed: _toggleIcon,
          ),
        ),
</code>```

But i don't know how to implement it because the input is a string.

I don't also know how to implement a Icon Class or is it even possible.

Please help me.

答:
You can use ValueNotifier with ValueListenableBuilder.

ValueNotifier<String> switchString = ValueNotifier("");

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: Column(
      children: [
        ValueListenableBuilder<String>(
          valueListenable: switchString,
          builder: (context, _iconState, child) {
            return Container(
              padding: const EdgeInsets.all(0),
              child: IconButton(
                padding: const EdgeInsets.all(0),
                alignment: Alignment.centerRight,
                icon: (switchString.value.contains('on')
                    ? const Icon(Icons.star)
                    : const Icon(Icons.star_border)),
                color: Colors.red[500],
                onPressed: () {},
              ),
            );
          },
        ),
        TextField(
          onChanged: (v) {
            switchString.value = v;
          },
        )
      ],
    ),
  );
}
```

Body:
I am new to flutter and i want to setState  a variable that will use to display an on and off icon. onPressed cannot be used because the input switch is a string.

void _toggleIcon() {
  setState(() {
      if (switch.contains('on')) {
        _iconState = true;
      } else if (switch.contains('off')) {
        _iconState = false;
      }
  });
}

I know that i can use the void function above on IconButton on onPressed using this code:

Container(
          padding: const EdgeInsets.all(0),
          child: IconButton(
            padding: const EdgeInsets.all(0),
            alignment: Alignment.centerRight,
            icon: (_iconState
                ? const Icon(Icons.star)
                : const Icon(Icons.star_border)),
            color: Colors.red[500],
            onPressed: _toggleIcon,
          ),
        ),

But i don't know how to implement it because the input is a string.

I don't also know how to implement a Icon Class or is it even possible.

Please help me.


问:
Deleting file from Digital Ocean Space with Next (NodeJs)
I encountered weird behavior, while trying to delete file from S3 bucket on digitaloceanspace. I use aws-sdk and I follow the official example. However, the method doesn't delete the file, no error occurs and returned data object (which should be a key of deleted item) is empty. Below the code:

```<code>import AWS from "aws-sdk";

export default async function handler(req, res){

  const key = req.query.key
  const spacesEndpoint = new AWS.Endpoint("ams3.digitaloceanspaces.com");
  const s3 = new AWS.S3({
      endpoint: spacesEndpoint,
      secretAccessKey: process.env.AWS_SECRET_KEY,
      accessKeyId: process.env.AWS_ACCESS_KEY,
  });

  const params = {
      Bucket: process.env.BUCKET_NAME,
      Key: key,
  };

  s3.deleteObject(params, function (error, data) {
      if (error) {
          res.status({ error: "Something went wrong" });
      }
      console.log("Successfully deleted file", data);
  });
}
</code>```

The environmental variables are correct, the other (not mentioned above) upload file method works just fine.

The key passed to the params has format 'folder/file.ext' and it exists for sure.

What is returned from the callback is log: 'Successfully deleted file {}'

Any ideas what is happening here?

答:
Please make sure you don't have any spaces in your key (filename), otherwise, it won't work. I was facing a similar problem when I saw there was a space in the filename that I was trying to delete.

Let's have an example if we are trying to upload a file named "new file.jpeg", then the DigitalOcean space is going to save it as "new\20%file.jpeg" and when you will try to delete this file, it won't find any file having name as "new file.jpeg". That's why we need to trim any whitespace or space between the words in the file name.

Hope it helps.

Body:
I encountered weird behavior, while trying to delete file from S3 bucket on digitaloceanspace. I use aws-sdk and I follow the official example. However, the method doesn't delete the file, no error occurs and returned data object (which should be a key of deleted item) is empty. Below the code:

import AWS from "aws-sdk";

export default async function handler(req, res){

  const key = req.query.key
  const spacesEndpoint = new AWS.Endpoint("ams3.digitaloceanspaces.com");
  const s3 = new AWS.S3({
      endpoint: spacesEndpoint,
      secretAccessKey: process.env.AWS_SECRET_KEY,
      accessKeyId: process.env.AWS_ACCESS_KEY,
  });

  const params = {
      Bucket: process.env.BUCKET_NAME,
      Key: key,
  };

  s3.deleteObject(params, function (error, data) {
      if (error) {
          res.status({ error: "Something went wrong" });
      }
      console.log("Successfully deleted file", data);
  });
}

The environmental variables are correct, the other (not mentioned above) upload file method works just fine.

The key passed to the params has format 'folder/file.ext' and it exists for sure.

What is returned from the callback is log: 'Successfully deleted file {}'

Any ideas what is happening here?


问:
Sending a list of gst::Structure from rust gstreamer plugin to c++
I'm developing a GStreamer plugin using Rust. I want to send back an array of objects from rust to c++. Each object has two fields. word and confidence. I tried this code. but it did not compile. I can send the structure whenever it just has text. But when I want to add words, I couldn't make it compile at all.

```<code>let v = vec![];
for word in transcript.words {
    v.push(gst::Structure::new("word-info",
    &[("word", &word.word), ("confidence", &word.confidence)]));
}

let structure = gst::Structure::new(
    "result",
    &[
        ("text", &transcript.text),
        ("words", &gst::Array::from(&v[..]))
    ],
);

element
    .emit_by_name("new-transcript", &[&structure])
    .unwrap();
</code>```

So I want to send back structure. It has two fields. text and words. words is a list of (word, confidence) pairs.

答:
Just minor changes were needed. I had to send a vector of SendValue to gst::Array::from_owned

```<code>let v = vec![];
for word in transcript.words {
    v.push(gst::Structure::new("word-info",
    &[("word", &word.word), ("confidence", &word.confidence)]).to_send_value());
}

let structure = gst::Structure::new(
    "result",
    &[
        ("text", &transcript.text),
        ("words", &gst::Array::from_owned(&v[..]))
    ],
);

element
    .emit_by_name("new-transcript", &[&structure])
    .unwrap();
</code>```

Body:
I'm developing a GStreamer plugin using Rust. I want to send back an array of objects from rust to c++. Each object has two fields. word and confidence. I tried this code. but it did not compile. I can send the structure whenever it just has text. But when I want to add words, I couldn't make it compile at all.

let v = vec![];
for word in transcript.words {
    v.push(gst::Structure::new("word-info",
    &[("word", &word.word), ("confidence", &word.confidence)]));
}

let structure = gst::Structure::new(
    "result",
    &[
        ("text", &transcript.text),
        ("words", &gst::Array::from(&v[..]))
    ],
);

element
    .emit_by_name("new-transcript", &[&structure])
    .unwrap();

So I want to send back structure. It has two fields. text and words. words is a list of (word, confidence) pairs.

Body:
Just minor changes were needed. I had to send a vector of SendValue to gst::Array::from_owned

let v = vec![];
for word in transcript.words {
    v.push(gst::Structure::new("word-info",
    &[("word", &word.word), ("confidence", &word.confidence)]).to_send_value());
}

let structure = gst::Structure::new(
    "result",
    &[
        ("text", &transcript.text),
        ("words", &gst::Array::from_owned(&v[..]))
    ],
);

element
    .emit_by_name("new-transcript", &[&structure])
    .unwrap();


问:
Property 'name' does not exist on type 'Object' ts(2339) for React and Ionic project
So I am building a React + Ionic + Typescript project. I am using the React hooks to set an array of objects. I then map through that array of objects and am trying to access a certain key in that object but it is saying that it doesn't exist (challenge.name).

```<code>const FindChallenges: React.FC = () => {
  const { isAuthenticated } = useAuth0();
  const [searchedChallenge, setSearchedChallenge] = useState<string>(); // what user searched.
  const [allChallenges, setAllChallenges] = useState<Array<Object>>([]); // the challenges that match search.
  // const [test, setTest] = useState<Array<Object>>([{1:"test"}, {2: "hello"}, {3: "world"}]);

  // Only works for web right now.
  // Will need to set up PORT forwarding for ios/android.
  const API_URL = "http://localhost:3001";

  useEffect(() => {
    // if (!isAuthenticated) return;
    fetch(API_URL + "/api/getAllChallenges", {
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }
    })
      .then(data => data.json())
      .then(res => {
        let results = [];
        for (let key in res) {
          results.push(res[key])
        }
        setAllChallenges(results);

      })
  }, []);

  if (!isAuthenticated) return (<PageLock />);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    console.log("FORM SUBMITTED");
    // setSearchedChallenge("");
  }

  return (
    <IonPage>
      <IonHeader>
        <IonToolbar>
          <IonTitle className="ion-text-center">Find a Challenge</IonTitle>
        </IonToolbar>
      </IonHeader>
      <IonContent fullscreen>
        {/* <IonHeader collapse="condense">
          <IonToolbar>
            <IonTitle size="large">Find ChallengesTab</IonTitle>
          </IonToolbar>
        </IonHeader> */}
        <IonCard>
          {/* <IonItem>
            <IonLabel className="ion-text-center" id="profileLabel">Your Challenges</IonLabel>
          </IonItem> */}
          <IonCardContent id="ionCardContent">
            <form onSubmit={handleSubmit}>
              <IonInput clear-input="true" id="search-challenge-input" value={searchedChallenge} placeholder="Enter Input" onIonChange={e => setSearchedChallenge(e.detail.value!)}></IonInput>
              <IonButton expand="block" type="submit" className="ion-margin-top">
                Search
              </IonButton>
            </form>
          </IonCardContent>
        </IonCard>
        <br></br>
        {console.log(allChallenges)}
        <IonCard>

          {allChallenges.map(challenge => (
            // <IonItem href="#" className="ion-activated">
            //   <IonLabel>{challenge}</IonLabel>
            // </IonItem>
            <div>
              <>{console.log(challenge)}</>
              <>{console.log(challenge.name)}</>
              {/* <>{challenge.key}</> */}
            </div>
          ))}

        </IonCard>
      </IonContent>
    </IonPage>
  );
};
</code>```

This is how the object is structured (when you console.log(challenges) in the map function), and it clearly has the "name" key, so why is it coming up as unknown??

答:
before the allchallenges state set in the useEffect it's empty and it doesn't have any name in it you can do two things first:

```<code>const [allChallenges, setAllChallenges] = useState<Array<Object>>([{name:"", key:0}]);
</code>```

and the second one you can set a boolean state after fetch like isOK and then turn it true after you got the result and use it like this:

```<code>  const [isOK , SetIsOK] = useState(false);

    {isOK && allChallenges.map(challenge => (
                // <IonItem href="#" className="ion-activated">
                //   <IonLabel>{challenge}</IonLabel>
                // </IonItem>
                <div>
                  <>{console.log(challenge)}</>
                  <>{console.log(challenge.name)}</>
                  {/* <>{challenge.key}</> */}
                </div>
              ))}
</code>```

Body:
So I am building a React + Ionic + Typescript project. I am using the React hooks to set an array of objects. I then map through that array of objects and am trying to access a certain key in that object but it is saying that it doesn't exist (challenge.name).

const FindChallenges: React.FC = () => {
  const { isAuthenticated } = useAuth0();
  const [searchedChallenge, setSearchedChallenge] = useState<string>(); // what user searched.
  const [allChallenges, setAllChallenges] = useState<Array<Object>>([]); // the challenges that match search.
  // const [test, setTest] = useState<Array<Object>>([{1:"test"}, {2: "hello"}, {3: "world"}]);

  // Only works for web right now.
  // Will need to set up PORT forwarding for ios/android.
  const API_URL = "http://localhost:3001";

  useEffect(() => {
    // if (!isAuthenticated) return;
    fetch(API_URL + "/api/getAllChallenges", {
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }
    })
      .then(data => data.json())
      .then(res => {
        let results = [];
        for (let key in res) {
          results.push(res[key])
        }
        setAllChallenges(results);

      })
  }, []);

  if (!isAuthenticated) return (<PageLock />);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    console.log("FORM SUBMITTED");
    // setSearchedChallenge("");
  }

  return (
    <IonPage>
      <IonHeader>
        <IonToolbar>
          <IonTitle className="ion-text-center">Find a Challenge</IonTitle>
        </IonToolbar>
      </IonHeader>
      <IonContent fullscreen>
        {/* <IonHeader collapse="condense">
          <IonToolbar>
            <IonTitle size="large">Find ChallengesTab</IonTitle>
          </IonToolbar>
        </IonHeader> */}
        <IonCard>
          {/* <IonItem>
            <IonLabel className="ion-text-center" id="profileLabel">Your Challenges</IonLabel>
          </IonItem> */}
          <IonCardContent id="ionCardContent">
            <form onSubmit={handleSubmit}>
              <IonInput clear-input="true" id="search-challenge-input" value={searchedChallenge} placeholder="Enter Input" onIonChange={e => setSearchedChallenge(e.detail.value!)}></IonInput>
              <IonButton expand="block" type="submit" className="ion-margin-top">
                Search
              </IonButton>
            </form>
          </IonCardContent>
        </IonCard>

        {console.log(allChallenges)}
        <IonCard>

          {allChallenges.map(challenge => (
            // <IonItem href="#" className="ion-activated">
            //   <IonLabel>{challenge}</IonLabel>
            // </IonItem>

              <>{console.log(challenge)}</>
              <>{console.log(challenge.name)}</>
              {/* <>{challenge.key}</> */}

          ))}

        </IonCard>
      </IonContent>
    </IonPage>
  );
};

This is how the object is structured (when you console.log(challenges) in the map function), and it clearly has the "name" key, so why is it coming up as unknown??

Body:
before the allchallenges state set in the useEffect it's empty and it doesn't have any name in it you can do two things first:

const [allChallenges, setAllChallenges] = useState<Array<Object>>([{name:"", key:0}]);

and the second one you can set a boolean state after fetch like isOK and then turn it true after you got the result and use it like this:

  const [isOK , SetIsOK] = useState(false);

    {isOK && allChallenges.map(challenge => (
                // <IonItem href="#" className="ion-activated">
                //   <IonLabel>{challenge}</IonLabel>
                // </IonItem>
                <div>
                  <>{console.log(challenge)}</>
                  <>{console.log(challenge.name)}</>
                  {/* <>{challenge.key}</> */}
                </div>
              ))}


问:
Can an OpenAL source ever be 0?
Can an OpenAL source generated by alGenSources() ever be 0?

Because I would like to store NULL as source whenever the source has stopped playing.

It is stored as an ALuint.

I couldn't find it in the Programmers guide.

答:
Unfortunately, you cannot rely on 0 being reserved as invalid, as it is allowed id by specs (up to implementation to decide).

According to OpenAL 1.1 specs:

2.12. Requesting Object Names

OpenAL provides calls to obtain object names.
The application requests a number of objects of a given category using alGen{Object}s. The actual values of the names returned are implementation dependent.
No guarantees on range or value are made.

...

void alGenBuffers (ALsizei n, ALuint *bufferNames);

void alGenSources (ALsizei n, ALuint *sourceNames);

From the other side, if you don't care about other OpenAL implementations, OpenAL soft (as for 1.17) internally returns values starting from 1, though this should be considered as implementation detail:

```<code>AL_API ALvoid AL_APIENTRY alGenSources(ALsizei n, ALuint *sources)
{
        ...
        err = NewThunkEntry(&source->id);
        ...
        sources[cur] = source->id;
}

ALenum NewThunkEntry(ALuint *index)
{
    ...
    *index = i+1;
    return AL_NO_ERROR;
}
</code>```

Title: Can an OpenAL source ever be 0?

Body:
Unfortunately, you cannot rely on 0 being reserved as invalid, as it is allowed id by specs (up to implementation to decide).

According to OpenAL 1.1 specs:

2.12. Requesting Object Names

OpenAL provides calls to obtain object names.
The application requests a number of objects of a given category using alGen{Object}s. The actual values of the names returned are implementation dependent.
No guarantees on range or value are made.

...

void alGenBuffers (ALsizei n, ALuint *bufferNames);

void alGenSources (ALsizei n, ALuint *sourceNames);

From the other side, if you don't care about other OpenAL implementations, OpenAL soft (as for 1.17) internally returns values starting from 1, though this should be considered as implementation detail:

AL_API ALvoid AL_APIENTRY alGenSources(ALsizei n, ALuint *sources)
{
        ...
        err = NewThunkEntry(&source->id);
        ...
        sources[cur] = source->id;
}

ALenum NewThunkEntry(ALuint *index)
{
    ...
    *index = i+1;
    return AL_NO_ERROR;
}