What do these strange values of padding mean in Microsoft's Fluent-react library? - fluentui-react

In this link, the section [Vertical Stack - Gap and Padding Sizes], click [Show code], then at lines 30, 34, 38, etc. I see some strange values of padding (and some of childrenGap) like 'm 40px', 's1', 's2', 'l1', and have no idea what they mean or where they are defined.
I tried to play around its code and not sure where to go next after the line 9 in this file.
Could someone please point me to their definition or document?
Thank you.

After a lot of digging, I found this in the Fluent source code. I'm not confident that's what's in play here, but circumstantial evidence points in that direction.
export const DefaultSpacing: ISpacing = {
s2: '4px',
s1: '8px',
m: '16px',
l1: '20px',
l2: '32px',
};

Related

GeoCode Results: Index Out of Range

I am making a code that converts an address into lat-long coordinates. I expected the program to output something along the lines of: 39.962714, -83.003419, but it returned an index error:
File "main.py", line 10, in <module>
result = requests.get('http://maps.googleapis.com/maps/api/geocode/json', params=params).json()['results'][0]
IndexError: list index out of range
python3 exited with code 1...
I haven't tried much because I couldn't find any situations similar to mine, and I don't understand exactly why the error message is coming up, because there should be at least one value in results but here's my code anyway:
'address': '90 W Broad St',
'sensor': 'false',
'region': 'Ohio'
}
result = requests.get('http://maps.googleapis.com/maps/api/geocode/json', params=params).json()['results'][0]
geodata = dict()
geodata['lat'] = result['geometry']['location']['lat']
geodata['lng'] = result['geometry']['location']['lng']
print('{lat}, {lng}'.format(**geodata))
I am very sorry if the answer is obvious, but thank you for your time reading this. :)

Finding the Start and End char indices in Spacy

I am training a custom model in Spacy to extract custom entities but while I need to provide an input train data that consists of my entities along with the index locations, I wanted to understand if there's a faster way to assign the index value for keywords I am looking for in a particular sentence in my training data.
An example of my traning data:
TRAIN_DATA = [
('Behaviour Skills include Communication, Conflict Resolution, Work Life Balance,
{'entities': [(25, 37, 'BS'),(40, ,60, 'BS'),(62, 79, 'BS')]
})
]
Now to pass the index location for specific keywords in my training data, I am presently counting it manually to give the location of my keyword.
For example: in case of the first line where I am saying Behaviour skills include Communication etc, I am manually calculating the location of the index for the word "Communication" which is 25,37.
I am sure there must be another way to identify the location of these indices by some other methods instead counting it manually. Any ideas how can I achieve this?
Using str.find() can help here. However, you have to loop through both sentences and keywords
keywords = ['Communication', 'Conflict Resolution', 'Work Life Balance']
texts = ['Behaviour Skills include Communication, Conflict Resolution, Work Life Balance',
'Some sentence where lower case conflict resolution is included']
LABEL = 'BS'
TRAIN_DATA = []
for text in texts:
entities = []
t_low = text.lower()
for keyword in keywords:
k_low = keyword.lower()
begin = t_low.find(k_low) # index if substring found and -1 otherwise
if begin != -1:
end = begin + len(keyword)
entities.append((begin, end, LABEL))
TRAIN_DATA.append((text, {'entities': entities}))
Output:
[('Behaviour Skills include Communication, Conflict Resolution, Work Life Balance',
{'entities': [(25, 38, 'BS'), (40, 59, 'BS'), (61, 78, 'BS')]}),
('Some sentence where lower case conflict resolution is included',
{'entities': [(31, 50, 'BS')]})]
I added str.lower() just in case you might need it.

OSM XML to GEOJSON in Python

I am trying to learn Python and Open Street Map API. I want to download with python a small region and then convert it into Geojson. I tried with two python libraries(osm2geojson and osmtogeojson) to convert OSM xml to Geojson so far but I am getting errors in both of them. My code is the following using osm2geojson:
from OSMPythonTools.api import Api
api = Api()
bbox = api.query('map?bbox=-0.08918,51.47980,-0.08496,51.48128')
import osm2geojson
geojson = osm2geojson.xml2geojson(bbox.toXML())
My exception with osm2geojson is the following:
line 264, in multiline_realation_to_shape
refs_index[member['ref']]['used'] = rel['id']
KeyError: 8835435
and with osmtogeojson the exception is:
line 21, in _preprocess
for elem in j["elements"]:
TypeError: string indices must be integers
What am I doing wrong?
If you print the type of bbox:
print(type(bbox))
<class 'OSMPythonTools.api.ApiResult'>
You can try it:
print(bbox.tags())
{'alt_name': 'London Cycle Network route 23',
'colour': '#0198E1',
'cycle_network': 'GB:London Cycle Network',
'name': 'LCN 23',
'network': 'lcn',
'ref': '23',
'ref:colour': '#0198E1',
'ref:colour_bg': 'white',
'ref:colour_tx': 'white',
'route': 'bicycle',
'type': 'route'}
print(type(bbox.tags()))
<class 'dict'>
https://github.com/mocnik-science/osm-python-tools/blob/master/docs/element.md
One way to do this (although not through python) is to use the ogr library.
Download and install the library, then:
ogr2ogr -f "GeoJSON" ".outputFile.geojson" "inputFile.osm" lines
Please note that due to the different way each format handles layers, you may have to change the last argument from lines to whichever layer you are interested in.
Also see this link.

Reducing time and memory used in loop calculation when locating earthquakes

I'm trying to locate tremor, which is a type of earthquake with smaller amplitude. I use grid search, which is a method that finds the coordinate where 'the difference between theoretical value and observed value of differential time in seismic wave arrival' becomes minimum.
The code I made is as follows. First I defined two functions that calculate distance between earthquake source and each point on grid, and that calculate travel time of seismic waves using obspy.
def distance(a,i):
return math.sqrt(((ste[a].stats.sac.stla-la[i])**2)+((ste[a].stats.sac.stlo-lo[i])**2))
def traveltime(a):
return model.get_travel_times(source_depth_in_km=35, distance_in_degree=a, phase_list=["S"], receiver_depth_in_km=0)[0].time
Then I conducted grid search using following codes.
di=[(la[i],lo[i],distance(a,i), distance(b,i)) for i in range(len(lo))
for a in range(len(ste))
for b in range(len(ste)) if a<b]
didf=pd.DataFrame(di)
latot=didf[0]
lotot=didf[1]
dia=didf[2]
dib=didf[3]
tt=[]
for i in range(len(di)):
try:
tt.append((latot[i],lotot[i],traveltime(dia[i])-traveltime(dib[i])))
except IndexError:
continue
ttdf=pd.DataFrame(tt)
final=[(win[j],ttdf[0][i],ttdf[1][i],(ttdf[2][i]-shift[j])**2) for i in range(len(ttdf))
for j in range(len(ccdf))]
where la and lo are the list of latitude and longitude coordinates with 0.01 degree interval, and ste is the list of the east components seismogram of each station. I have to get the list 'final' to proceed to the next step.
However, the problem is that it takes too much time to calculate three segments of codes written above. Moreover, the result I get after tens of hours of calculation is 'out of memory' error message. Is there any solution that can reduce both time and memory?
Without access to your dataset, it's a little difficult to debug, but here are a few suggestions for you.
for i in range(len(di)):
try:
tt.append((latot[i],lotot[i],traveltime(dia[i])-traveltime(dib[i])))
except IndexError:
continue
• Given the size of these lists, I think that the Garbage Collector might be slowing down this for loop; you might consider turning it off for the duration of the loop (gc.disable()).
• In theory, the Append statement shouldn't be the source of your performance problems, since it over-allocates:
/* This over-allocates proportional to the list size, making room
* for additional growth. The over-allocation is mild, but is
* enough to give linear-time amortized behavior over a long
* sequence of appends() in the presence of a poorly-performing
* system realloc().
* The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
*/
new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6);
but you already know the size of the array, so you might consider using numpy.zeroes() to fill the list before the for-loop, and use the index to directly address each element. Alternatively, you could just use list comprehensions, as you did earlier, and avoid the problem altogether.
• I see that you've tagged the question with python-3.x, so range() shouldn't be an issue like it was in 2.x (otherwise you would want to consider using xrange()).
If you update your question with more details, I could probably provide a more detailed answer...hope this helps.

Detect Color of particular area of Image Nodejs OpenCV

I'm trying to write code to detect the color of a particular area of an image.
So far I have come across is using OpenCV, we can do this, But still haven't found any particular tutorial to help with this.
I want to do this with javascript, but I can also use python OpenCV to get the results.
can anyone please help me with sharing any useful link or can explain how can I achieve detecting the color of the particular area in the image.
For eg.
The box in red will show a different color. I need to figure out which color it is showing.
What I have tried:
I have tried OpenCV canny images, though I am successful to get area separated with canny images, how to detect the color of that particular canny area is still a challenge.
Also, I tried it with inRange method from OpenCV which works perfect
# find the colors within the specified boundaries and apply
# the mask
mask = cv2.inRange(image, lower, upper)
output = cv2.bitwise_and(image, image, mask = mask)
# show the images
cv2.imshow("images", np.hstack([image, output]))
It works well and extracts the color area from the image But is there any callback which responds if the image has particular color so that it can be all done automatically?
So I am assuming here that, you already know the location of the rect which is going to be dynamically changed and need to find out the single most dominant color in the desired ROI. There are a lot of ways to do the same, one is by getting the average, of all the pixels in the ROI, other is to count all the distinct pixel values in the given ROI, with some tolerance difference.
Method 1:
import cv2
import numpy as np
img = cv2.imread("path/to/img.jpg")
region_of_interest = (356, 88, 495, 227) # left, top, bottom, right
cropped_img = img[region_of_interest[1]:region_of_interest[3], region_of_interest[0]:region_of_interest[2]]
print cv2.mean(cropped_img)
>>> (53.430516018839604, 41.05708814243569, 244.54991977640907, 0.0)
Method 2:
To find out the various dominant clusters in the given image you can use cv2.kmeans() as:
import cv2
import numpy as np
img = cv2.imread("path/to/img.jpg")
region_of_interest = (356, 88, 495, 227)
cropped_img = img[region_of_interest[1]:region_of_interest[3], region_of_interest[0]:region_of_interest[2]]
Z = cropped_img.reshape((-1, 3))
Z = np.float32(Z)
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
K = 4
ret, label, center = cv2.kmeans(Z, K, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
# Sort all the colors, as per their frequencies, as:
print center[sorted(range(K), key=lambda x: np.count_nonzero(label == [x]), reverse=True)[0]]
>>> [ 52.96525192 40.93861389 245.02325439]
#Prateek... nice to have the question narrowed down to the core. The code you provided does not address this issue at hand and remains just a question. I'll hint you towards a direction but you have to code it yourself.
steps that guide you towards a scripting result:
1) In your script add two (past & current) pixellists to store values (pixeltype + occurance).
2) Introduce a while-loop with an action true/stop statement (link to "3") for looping purpose because then it becomes a dynamic process.
3) Write a GUI with a flashy warning banner.
4) compare the pixellist with current_pixellist for serious state change (threshhold).
5) If the delta state change at "4" meets threshold throw the alert ("3").
When you've got written the code and enjoyed the trouble of tracking the tracebacks... then edit your question, update it with the code and reshape your question (i can help wiht that if you want). Then we can pick it up from there. Does that sound like a plan?
I am not sure why you need callback in this situation, but maybe this is what you mean?
def test_color(image, lower, upper):
mask = cv2.inRange(image, lower, upper)
return np.any(mask == 255)
Explanations:
cv2.inRange() will return 255 when pixel is in range (lower, upper), 0 otherwise (see docs)
Use np.any() to check if any element in the mask is actually 255

Resources