<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Amine Daoud on Medium]]></title>
        <description><![CDATA[Stories by Amine Daoud on Medium]]></description>
        <link>https://medium.com/@daoud-amin7?source=rss-2567a0deb43a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GqJoQO4zG5QrN_Y9cbBsSg.png</url>
            <title>Stories by Amine Daoud on Medium</title>
            <link>https://medium.com/@daoud-amin7?source=rss-2567a0deb43a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 11:58:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@daoud-amin7/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Scrape Restaurants Using Google Maps API]]></title>
            <link>https://daoud-amin7.medium.com/how-to-scrape-restaurants-using-google-maps-api-eb13889cb7e8?source=rss-2567a0deb43a------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb13889cb7e8</guid>
            <category><![CDATA[scraping-with-python]]></category>
            <category><![CDATA[google-maps-api]]></category>
            <category><![CDATA[google-places-api]]></category>
            <category><![CDATA[scraping]]></category>
            <category><![CDATA[google-map-api]]></category>
            <dc:creator><![CDATA[Amine Daoud]]></dc:creator>
            <pubDate>Fri, 21 Apr 2023 20:43:48 GMT</pubDate>
            <atom:updated>2023-04-21T21:04:37.498Z</atom:updated>
            <content:encoded><![CDATA[<p>Using Google Maps API is a fantastic way to discover new food options and gems in your area, find out which restaurants are the most popular, and avoid the worst ones. However, it’s essential to note that Google Maps API does not return a complete list of restaurants in a city or even around an address in a single request, and the results may differ from one neighborhood to another.</p><p>The first step is to obtain a Google Maps API key to make requests. After that, you’ll need to create a list of addresses in your city that will be used for multiple requests. For example, to obtain restaurants in Paris, I created a list of the addresses of each neighborhood in the 20 districts of Paris and added the addresses of metro stations to get more relevant results, since many restaurants are close to these stations.</p><p>Next, you’ll need to create a map of coordinates that cover the search area. You can generate the coordinates of metro stations from a file containing the metro names using the code below. This code will write the coordinates to ‘metro_points.csv’:</p><pre>import googlemaps<br>import pandas as pd<br><br>gmaps = googlemaps.Client(key=&#39;YOUR-API-KEY&#39;)<br><br>csv_file_name = &#39;metro_points.csv&#39;<br><br>with open(csv_file_name, &quot;w&quot;, encoding=&quot;utf-8&quot;, newline=&#39;&#39;) as f:<br>     # Write the header row<br>     f.write(&quot;latitude,longitude\n&quot;)<br><br>import pandas as pd<br>metros_df = pd.read_csv(&quot;metros.txt&quot;, header=None, names=[&quot;metro_name&quot;])<br>for index, row in metros_df.iterrows():<br>    metro = row[&quot;metro_name&quot;]<br>    query_station = &quot;metro &quot; + metro + &quot; Paris&quot;<br>    place = gmaps.geocode(query_station)<br>    place_info = place[0]<br>    geo_results = place_info[&#39;geometry&#39;]<br>    geo_coordinates = geo_results[&#39;location&#39;]<br>    lat = geo_coordinates[&#39;lat&#39;]<br>    lng = geo_coordinates[&#39;lng&#39;]<br>    point_df = pd.DataFrame({&#39;latitude&#39;: [lat], &#39;longitude&#39;: [lng]})<br>    with open(csv_file_name, mode=&#39;a&#39;, encoding=&quot;utf-8&quot;, newline=&#39;&#39;) as csvfile:<br>        point_df.to_csv(csvfile, mode=&#39;a&#39;, header=False, index=False, line_terminator=&#39;\n&#39;)</pre><p>If you visualize the coordinates on the map using the folium library, you’ll be able to identify any missing spots.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eiYkF-RsdkkjZvXuO0wMfA.png" /></figure><p>You can also do the same thing with the names of neighborhoods to get more addresses. Additionally, to increase the number of results, you can apply an algorithm that adds more markers based on existing ones to cover each specific small radius in the city (e.g., 500 meters).</p><p>After generating these markers, you can aggregate them in a single CSV file and use them to get the restaurants in your city. Here’s an example of how to retrieve restaurants for each address:</p><pre>points_df = pd.read_csv(&quot;points.csv&quot;, header=0)<br>for i in range(len(points_df)-1, -1, -1):<br>    point = points_df.iloc[i]    <br>    j+=1<br>    flag = False<br>    counter = 0<br>    lat = point[&#39;latitude&#39;]<br>    lng = point[&#39;longitude&#39;]<br>    while not flag:<br>        if counter == 0:<br>            results = gmaps.places_nearby(type=&quot;restaurant&quot;, location=[<br>                                   lat, lng], rank_by=&quot;distance&quot;)<br>            response_items = results[&#39;results&#39;]<br>            restaurants_in_response = restaurant_response(response_items)<br>            writeToFile(restaurants_in_response)<br>            restaurants.extend(restaurants_in_response)<br>            counter += 1<br>        else:<br>            if results.get(&#39;next_page_token&#39;) is None:<br>                flag = True<br>            else:<br>                next_page = results.get(&#39;next_page_token&#39;)<br>                time.sleep(2)<br>                results = gmaps.places_nearby(type=&quot;restaurant&quot;, location=[<br>                                       lat, lng], rank_by=&quot;distance&quot;, page_token=next_page)<br>                response_items = results[&#39;results&#39;]<br>                restaurants_in_response = restaurant_response(response_items)<br>                writeToFile(restaurants_in_response)<br>                restaurants.extend(restaurants_in_response)<br>                counter += 1</pre><p>At first, I found around 2000 restaurants and by adding more markers on the map to cover more area and tweaking the places API by changing the radius, applying different criteria like sorting by relevance or by distance and also searching restaurants by cuisine type like Indian, Chinese, etc., I could finally get more than 16000 restaurants in Paris after aggregating the different results in a single Excel file.</p><p>Once I obtained a list of restaurants using the Google Maps API, I filtered and sorted the results to find the best restaurants in the city. I persisted the results in an Excel file and used various criteria such as rating and number of comments to filter the data.</p><p>For example, I sorted the restaurants by rating and only kept the ones with a rating of 4.0 or higher. I also filtered the restaurants based on the number of comments to only keep the ones with a significant number of reviews.</p><p>In the case of Paris, I was surprised that the restaurants belonging to the Big Mamma group were on the top of the list based on popularity and reviews, and that’s how I learned about them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w4rY1ddse3e3173dz1Qhng.png" /></figure><p>In conclusion, while the process was time-consuming and required various tweaks and adjustments to the search criteria and data, but the final result was worth the effort and provided valuable insights about the best restaurants in Paris.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb13889cb7e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stream API with examples in Java]]></title>
            <link>https://daoud-amin7.medium.com/stream-api-with-examples-in-java-625c31c1307a?source=rss-2567a0deb43a------2</link>
            <guid isPermaLink="false">https://medium.com/p/625c31c1307a</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[stream-api]]></category>
            <dc:creator><![CDATA[Amine Daoud]]></dc:creator>
            <pubDate>Sat, 10 Sep 2022 19:47:05 GMT</pubDate>
            <atom:updated>2022-09-10T19:47:05.787Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In this article, we will explore the Stream API that was introduced in Java 8 and it’s one of the main functional programming APIs in Java.</p><p>A stream has no storage, it’s not a data structure as many might think, it just uses a source like a collection and transform it through a series of multiple operations to a destination. In these operations, there could be multiple intermediate operations and only one terminal operation that consumes the stream such as <em>foreach </em>and <em>collect</em><strong>.</strong></p><p>The stream doesn’t change the source and so it produces a new result.</p><p>After a stream is consumed by a terminal operation, it cannot be consumed again and a new stream shall be created otherwise you will get <strong>java.lang.IllegalStateException: stream has already been operated upon or closed.</strong></p><p>Most Stream operations are always implemented in a lazy way in order to seek performance by aggregating multiple operations together.</p><p>As a example, if you want to filter names starting with “M” then return the first element. The filter operation will just find the first element starting with ‘M’ and the stream will be consumed immediately. So, <em>filter </em>and <em>findFirst </em>operations are combined together. Below is an example that demonstrates this.</p><pre>Stream&lt;String&gt; st = Stream.<em>of</em>(&quot;Marc&quot;, &quot;Helen&quot;, &quot;Mario&quot;, &quot;Sarah&quot;);<br>Optional&lt;String&gt; res = st.filter(s -&gt; s.startsWith(&quot;M&quot;)).peek(s -&gt; System.<em>out</em>.println(&quot;debug &quot; +  s)).findFirst();<br>System.<em>out</em>.println(res.get());</pre><p>If we add a <em>peek </em>between the <em>filter </em>and <em>findFirst </em>for debugging purposes, we can that filter has been applied only on the first name starting with “M”.</p><pre>debug Marc<br>Marc</pre><h3>Stream operations</h3><h3>1. map</h3><p><em>map </em>is one of the most common stream operations. It’s an intermediate operation and it returns a new Stream after applying a function to each element of the stream.</p><p>In the below example, we want to transform words in uppercase. collect is used as a terminal operation to indicate the structure that should be returned (in this case a list).</p><pre>List<strong>&lt;</strong>String<strong>&gt;</strong> animals <strong>=</strong> List.of(&quot;Dog&quot;, &quot;Rabbit&quot;, &quot;Cat&quot;, &quot;Mouse&quot;, &quot;Bird&quot;);<br>System.out.println(animals.stream().map(String::toUpperCase).collect(toList()));</pre><pre>--------------------------------------------------------------------</pre><pre>[DOG, RABBIT, CAT, MOUSE, BIRD]</pre><p>We can also collect the result to a set or concatenate the list elements like below.</p><pre>System.out.println(animals.stream().map(String::toUpperCase).collect(joining(&quot;|&quot;)));</pre><pre>--------------------------------------------------------------------</pre><pre>DOG|RABBIT|CAT|MOUSE|BIRD</pre><h3>2. forEach</h3><p><em>forEach </em>is a terminal operation and it allows to iterate over the elements of a stream and apply a function for each element. In the below case, we want to print each element in the stream:</p><pre>Stream<strong>&lt;</strong>String<strong>&gt;</strong> st <strong>=</strong> Stream.of(&quot;house&quot;, &quot;car&quot;, &quot;laptop&quot;);<br>st.forEach(System.out::println);</pre><pre>--------------------------------------------------------------------</pre><pre>house<br>car<br>laptop</pre><h3>3. mapToInt</h3><p>We can use <em>mapToInt </em>to map a stream to primitive integer values. in the below example, we invoke then a terminal operation sum to calculate the sum of the stream elements.</p><pre>Stream<strong>&lt;</strong>String<strong>&gt;</strong> st <strong>=</strong> Stream.of(&quot;1&quot;, &quot;2&quot;, &quot;3&quot;);<br>st.mapToInt(Integer::parseInt).sum();</pre><pre>--------------------------------------------------------------------</pre><pre>6</pre><h3>4. sorted</h3><p><em>sorted </em>is another intermediate operation and used to arrange the order of stream elements following a provided comparator. In the below example, we want to sort the words following the ascendant order which is using <em>Comparator#reverseOrder</em>.</p><pre>Stream<strong>&lt;</strong>String<strong>&gt;</strong> st <strong>=</strong> Stream.of(&quot;house&quot;, &quot;car&quot;, &quot;laptop&quot;);<br>System.out.println(st.sorted(Comparator.reverseOrder()).collect(toList()));</pre><pre>--------------------------------------------------------------------</pre><pre>[laptop, house, car]</pre><h3>5. filter</h3><p><em>filter </em>is an intermediate operation which allows to select a subset of elements matching a condition. In the below example, we want to select only strings starting with letter ‘c’:</p><pre>Stream<strong>&lt;</strong>String<strong>&gt;</strong> st <strong>=</strong> Stream.of(&quot;house&quot;, &quot;car&quot;, &quot;laptop&quot;);<br>System.out.println(st.filter(str <strong>-&gt;</strong> str.startsWith(&quot;c&quot;)).collect(toList()));</pre><pre>--------------------------------------------------------------------</pre><pre>[car]</pre><h3>6. reduce</h3><p><em>reduce </em>is a terminal operation, it allows us to reduce multiple elements to one result following a reduction function like concatenating strings or adding integers.</p><p>In the below example, we want to create a string of comma separated words from the stream.</p><pre>Stream<strong>&lt;</strong>String<strong>&gt;</strong> st <strong>=</strong> Stream.of(&quot;house&quot;, &quot;car&quot;, &quot;laptop&quot;);<br>System.out.println(st.reduce((e1, e2) <strong>-&gt;</strong> e1 <strong>+</strong> &quot;, &quot; <strong>+</strong> e2));</pre><pre>--------------------------------------------------------------------</pre><pre>Optional[house, car, laptop]</pre><h3>7. distinct, limit , skip</h3><p>These operations are intermediate.</p><p><em>distinct </em>allows to return distinct elements of the list by comparing all the elements in the list using equals and removing duplicates.</p><p>Regarding <em>limit</em>, as the name suggests you can limit the results the first n elements of the stream.</p><p><em>skip </em>will let you skip n first elements from the stream and display the remaining elements.</p><pre>List<strong>&lt;</strong>Integer<strong>&gt;</strong> ints <strong>=</strong> List.of(2, 34,2, 5 , 7, 7, 7, 34, 17);</pre><pre>System.out.println(ints.stream().distinct().collect(toList()));<br>System.out.println(ints.stream().limit(2).collect(toList()));<br>System.out.println(ints.stream().skip(5).collect(toList()));</pre><pre>--------------------------------------------------------------------</pre><pre>[2, 34, 5, 7, 17]<br>[2, 34]<br>[7, 7, 34, 17]</pre><h3>8. min , max</h3><p><em>min</em> and <em>max </em>are terminal operations which allows to find the minimum and maximum values in a stream using a comparator. Both <em>min</em> and <em>max </em>returns an Optional as a result.</p><pre>List<strong>&lt;</strong>Integer<strong>&gt;</strong> ints <strong>=</strong> List.of(2, 34,2, 5 , 7, 7, 7, 34, 17);</pre><pre>System.out.println(ints.stream().min(Comparator.reverseOrder()));<br>System.out.println(ints.stream().max(Comparator.naturalOrder()));</pre><pre>--------------------------------------------------------------------</pre><pre>Optional[34]<br>Optional[34]</pre><h3>9. flatMap</h3><p><em>flatMap </em>is an intermediate operation. It’s useful when we operate on list of lists and want to access all the elements by flattening these lists.</p><p>In the below example, let’s consider a list of a list of integers. We want to find all the integers that are greater than 3 so we transform the <em>listOfLists </em>to a stream and then use <em>flatMap </em>method to flatten the lists and finally filter the matching elements using the condition.</p><pre>List<strong>&lt;</strong>List<strong>&lt;</strong>String<strong>&gt;&gt;</strong> listOfLists <strong>=</strong> List.of(List.of(&quot;1&quot;, &quot;2&quot;), List.of(&quot;3&quot;, &quot;4&quot;), List.of(&quot;5&quot;, &quot;6&quot;));<br>System.out.println(listOfLists.stream().flatMap(Collection::stream).filter(x<strong>-&gt;</strong> Integer.parseInt(x) <strong>&gt;</strong> 3).collect(toList()));</pre><pre>--------------------------------------------------------------------</pre><pre>[4, 5, 6]</pre><h3>10. allMatch, anyMatch, noneMatch</h3><p>All these operations are terminal.</p><p><em>allMatch</em> returns true if all elements in stream match a condition.</p><p><em>anyMatch </em>returns true if at least one element in stream match a condition.</p><p><em>noneMatch </em>returns true if all elements in the stream do not match the condition.</p><pre>List<strong>&lt;</strong>Integer<strong>&gt;</strong> ints <strong>=</strong> List.of(2, 34,2, 5 , 7, 7, 7, 34, 17);</pre><pre>System.out.println(ints.stream().allMatch(x <strong>-&gt;</strong> x<strong>&gt;</strong>1));<br>System.out.println(ints.stream().anyMatch(x <strong>-&gt;</strong> x<strong>==</strong>1));<br>System.out.println(ints.stream().noneMatch(x <strong>-&gt;</strong> x<strong>==</strong>17));</pre><pre>--------------------------------------------------------------------</pre><pre>true<br>false<br>false</pre><h3>11. peek</h3><p><em>peek </em>is an intermediate operation. It’s usually used to debug the elements of the stream during intermediate operations.</p><pre>Stream.of(&quot;one&quot;, &quot;two&quot;, &quot;three&quot;, &quot;four&quot;)<br>  .filter(e <strong>-&gt;</strong> e.length() <strong>&gt;</strong> 3)<br>  .peek(e <strong>-&gt;</strong> System.out.println(&quot;Filtered value: &quot; <strong>+</strong> e))<br>  .map(String::toUpperCase)<br>  .peek(e <strong>-&gt;</strong> System.out.println(&quot;Mapped value: &quot; <strong>+</strong> e))<br>  .collect(toList());</pre><pre>--------------------------------------------------------------------</pre><pre>Filtered value: three<br>Mapped value: THREE<br>Filtered value: four<br>Mapped value: FOUR</pre><pre>[THREE, FOUR]</pre><h3>12. Collect using groupingBy</h3><p><em>GroupingBy </em>is useful when we want to group the elements of the stream using a property.</p><p>In this example, we want to group the words by their frequency and return a frequency list corresponding to the distinct words and displayed in the natural order of the words.</p><pre>List<strong>&lt;</strong>String<strong>&gt;</strong> words <strong>=</strong> Arrays.asList(&quot;dog&quot;, &quot;cat&quot;, &quot;hello&quot;, &quot;cat&quot;, &quot;car&quot;, &quot;hello&quot;, &quot;hello&quot;);<br>Map<strong>&lt;</strong>String, Long<strong>&gt;</strong> res <strong>=</strong> words.stream().sorted().collect(<br>                  groupingBy(Function.identity(), LinkedHashMap::<strong>new</strong>, counting()));<br>System.out.println(res);</pre><pre>--------------------------------------------------------------------</pre><pre>{car=1, cat=2, dog=1, hello=3}</pre><h3>13. Collect using partioningBy</h3><p><em>partioningBy </em>allows to partition the results in a map with <em>boolean </em>keys. The values are a list of elements matching the condition for the true key and the false key is mapped to the elements not matching.</p><pre>List<strong>&lt;</strong>String<strong>&gt;</strong> st <strong>=</strong> List.of(&quot;cat&quot;, &quot;fish&quot;, &quot;dog&quot;, &quot;carl&quot;, &quot;fur&quot;);<br>System.out.println(st.stream().collect(partitioningBy(str<strong>-&gt;</strong> str.startsWith(&quot;d&quot;))));</pre><pre>--------------------------------------------------------------------</pre><pre>{false=[cat, fish, carl, fur], true=[dog]}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=625c31c1307a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>