<?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 AlpsCode on Medium]]></title>
        <description><![CDATA[Stories by AlpsCode on Medium]]></description>
        <link>https://medium.com/@alpscode?source=rss-bfd06ac27c77------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*YaV48bd4gewlu3K3.jpg</url>
            <title>Stories by AlpsCode on Medium</title>
            <link>https://medium.com/@alpscode?source=rss-bfd06ac27c77------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 03:45:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alpscode/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[Reflections from my first FPL season]]></title>
            <link>https://medium.com/@alpscode/reflections-from-my-first-fpl-season-693fc8237543?source=rss-bfd06ac27c77------2</link>
            <guid isPermaLink="false">https://medium.com/p/693fc8237543</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[sports-analytics]]></category>
            <category><![CDATA[fantasy-football]]></category>
            <dc:creator><![CDATA[AlpsCode]]></dc:creator>
            <pubDate>Mon, 26 Jul 2021 02:00:00 GMT</pubDate>
            <atom:updated>2021-07-26T18:54:53.199Z</atom:updated>
            <content:encoded><![CDATA[<p>If you ask any Fantasy Premier League (FPL) player on Twitter about what word has been beaten to death last season, they’d likely respond with “optimal”. I must admit that I played a part in starting or fueling more than my fair share of these discussions…</p><blockquote><em>There are optimal ways to play FPL.</em></blockquote><blockquote><em>- Sertalp B. Çay (@sertalpbilal) </em><a href="https://twitter.com/sertalpbilal/status/1376578600854519808?ref_src=twsrc%5Etfw"><em>March 29, 2021</em></a></blockquote><p>It might come as a surprise to some that I had never heard of FPL before August of 2020, just a week before I went on vacation. It’s fair to say that my time off was spoiled (to a degree) after my dear colleague, Bas Belfi, challenged me in the upcoming FPL season with the aid of analytics. Like any sane person, I spent most of my time after that reading through rules, reviewing academic papers, and taking notes from every guide I came across on Reddit.</p><p>My personal aim of beating Bas in FPL turned into something different when I realized optimization had a reputation in the community as a tool that wouldn’t work well for FPL. Looking back, I understand people’s skepticism towards “optimization”-like tools as there are many nuances to FPL that these tools tend to gloss over. Part of the problem of having a bad reputation was the overuse of the word “optimal” without giving any context or clearly describing model restrictions.</p><h3>Modeling FPL</h3><p>FPL is a fantasy sports game, where every player creates a squad of 15 players from the Premier League that they manage for 38 gameweeks. It’s not a difficult game by definition but playing from the perspective of a “bot” requires significant work.</p><p>When people hear “model” in FPL, they immediately think of prediction models like those produced by FPLReview, Fantasy Football Fix, as well as individuals like Mikkel Tokvam. For this discussion, it’s important to explain what I mean by “model” since there are several types of models. The models I mentioned above are called “predictive models”, since they try to predict future performance. There is also another class of models called “prescriptive models” like optimization models which are used for generating decisions.</p><p>An optimization model could consume any kind of predictive model in order to produce a clear set of decisions. This is what’s mostly missing in FPL circles: optimization models. While there are certainly many bots attempting to play well in FPL, I never encountered anyone else discussing optimization when I started playing aside from seeing occasional posts about people using it for a week or two.</p><h3>First few weeks</h3><p>I finished a basic model based on <a href="https://fplreview.com/">FPLReview</a> ‘s prediction data before GW1 (gameweek 1, AKA the start of the season), but I didn’t have all the details due to limited time. My first GW in FPL went great! I was able to get 40 points from a single player (Salah as captain) and finished with 76 points. My rank was 475K out of over 6 million players. Over the following weeks I kept climbing ranks until GW5 and at which point I had reached 151K overall rank.</p><p>I have to confess that after a few GWs I felt that FPL, after all, seemed like a relatively easy game. Everything was going smooth until I had to add a chip policy to my model, as I had no idea what to do with my chips. Chips are “benefits” you can use at certain moments during the game. There are different chips and each chip can only played once, so a specific strategy needs to be considered for it. Unfortunately, adding a premature chip policy logic forced me to use my WC (wildcard) chip by GW6. I received only 31 points in the GW that I used my first WC in… That was the GW I started to take things a bit more seriously as my competitive side had started to kick in.</p><h3>Challenging the status quo</h3><p>Around this time, I started mentioning on Twitter how I was using optimization for FPL purposes. The first knee-jerk reaction you often get from people after mentioning the use of optimization models for FPL is “okay, but how did it perform?”. This reaction is due in part to the exaggerated expectation that these models should be perfect, similar to the AlphaZero program playing chess. Measuring a model’s performance using realized points is the wrong way to look at things though. FPL is a noisy problem with huge variance so asking how an algorithm has performed after only a few weeks (or even after a single season) will result in a poor answer.</p><p>If you are going to remember one thing from this post, it should be this:</p><p><strong>Optimization models are approximations of real-life problems under measurable and controllable conditions to help the decision making process.</strong></p><p>If a model can perfectly imitate the real-life problem, then you can apply its outcomes as-is. In order to reach that level of maturity, though, you need to iterate over infeasibilities and missing pieces. That’s how I approach business problems in my work: you build a model, talk to the customer, identify model weaknesses, and find ways to improve it until the model can capture the essence of the problem. If for some reason it’s not possible to create a perfect model, then you can use optimization as an intermediate step in the pipeline.</p><p>We have some complicated problems in real life that require significant time to make the optimization model the best it can be. If you have been following my journey on Twitter, the first model I used at the beginning of the FPL season is unrecognizable from the one I ended up with by week 38. Week-by-week I added features such as:</p><ul><li>Transfer policy (<em>by GW2</em>)</li><li>Chip usage (<em>by GW6</em>)</li><li>Multiple objectives for short-term vs long-term gains (<em>by GW17</em>)</li></ul><p>Along the way, I have got in touch with other players who are using optimization themselves, as well as others who are interested in hearing more about how optimization works and how I’ve applied it to FPL. I have certainly raised some awareness (or at least I hope) in the community about what optimization looks like in the real world. There is definitely a distaste towards “bots” playing FPL, which I understand. However, that doesn’t give cause to just ignoring the fact that optimization can work well in FPL.</p><h3>The good, the bad, &amp; the ugly</h3><p>I spent the rest of last season furthering my understanding of how to apply optimization within FPL. I have built a few different models for it:</p><ul><li>The base model that follows the MS thesis on the topic.</li><li>A <em>robust optimization model</em> to protect my rank against highly owned players.</li><li>A <em>multi-objective optimization model</em> to balance short-term (1 GW) and long-term (8 GWs) returns.</li><li>A <em>max-min optimization model</em> to maximize the lowest rated player on my team.</li></ul><p>Some of these models certainly worked better than others, but their shortcomings were not always readily apparent. The model I have used the most was the multi-objective model where I also benefited from visually seeing the <a href="https://en.wikipedia.org/wiki/Efficient_frontier">efficient frontier</a>.</p><p>The good things about my initial season were that:</p><ol><li>I managed to beat my colleague Bas by 14 points, and I also won the Bots vs Bots mini-league by 3 points.</li><li>I fully developed my model based on prediction data, which can work with multiple configurations.</li><li>I met many fascinating people who are interested in analytics and sports.</li><li>I saw people’s perception of optimization and optimal play starting to change for the better.</li><li>I learned more about the finer details of FPL, like dealing with DGWs (double gameweeks, where at least one team plays 2 games), the importance of carrying a positive budget ITB (in the bank) and rolling free transfers, and the impact of ownership ratios.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/0*oxt7WZNMm_KARf9P.jpg" /></figure><p>Among other things, I also started collecting my Python scripts within a public repo, which I later turned into an open-source webpage under the <a href="https://fploptimized.com/">fploptimized.com</a> domain. In turn, this also led me to learn about GitHub actions, CI/CD operations, d3 library, and many more useful tools because of my newfound interest in FPL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VypmiV-tPSmRL1hf.jpg" /></figure><p>The bad part was dealing with fixture uncertainties. As if it was not enough that football itself is a low-scoring game with lots of variance, erratic changes (like the MUN-LIV game getting cancelled and COVID-19 postponements) caused many weird schedule changes that I was not prepared for.</p><p>The ugly part was struggling to keep developing the models while having to submit decisions on a weekly basis. Some GWs I had no time to run the model closer to the deadline due to other responsibilities so I was forced to run models one day early and submit decisions based on it. I remember transferring out Rashford for a hit (points deduction) due to a possible injury, only for him to end up playing.</p><h3>Now and future of optimization in FPL</h3><p>I feel like I contributed to the FPL community by further explaining what optimization does and advocating for how useful it was throughout the season. It wasn’t my original purpose, but I enjoyed my transformation from a casual quantitative player to someone who applies optimization, writes about it, and creates tutorials for others to follow and learn from.</p><p>Anyone can build a model that can capture, say, 80%-90% of the FPL planning optimization problem easily. I have made a few videos on this very topic that make it easy to get into things. (Link to <a href="https://youtube.com/playlist?list=PLrIyJJU8_viOags1yudB_wyafRuTNs1Ed">Python</a> and <a href="https://youtube.com/playlist?list=PLrIyJJU8_viOLw3BovPDx5QLKkCb8XOTp">Excel</a> playlist.)</p><p>A closer-to-reality FPL model is unfortunately non-linear. Roughly, it means that the problem is difficult to solve perfectly. The non-linear nature of the problem comes from three sources as I can see:</p><ol><li>The probabilistic nature of player points.</li><li>The probabilistic nature of players being in the starting line-up or on the bench.</li><li>The auto-sub rules regarding valid formations.</li></ol><p>These are some of the things that still make FPL quite interesting for me, even after spending a full season playing it and dealing with <em>negative variance</em>.</p><p>I believe the next logical step for me is to determine the best input parameters that I can use. For this purpose, I have organized a “re-optimization competition” to find good values for optimization parameters that a decision maker should control. Basically, competitors submitted their belief of how certain actions should be valued which I ran through my optimization model for the entire season, using <a href="https://fplreview.com/">FPLReview</a> data. At the end, I saw what I was thinking: even following an oversimplified setting, you can score a great amount of points (2482 was the maximum among entries) by only using optimization. It might be a hard pill to swallow, but I think there is a silver lining.</p><h3>Augmented Intelligence</h3><p>The ideal setting for FPL optimization is that it should be used by people who follow the news about players, understand the game to a certain extent, and are open to analytical approaches.</p><p>Rather than dictating their decisions on gut feelings, optimization can provide them answers to complex questions that we cannot reach quickly. This human-centered concept is called <a href="https://www.gartner.com/en/information-technology/glossary/augmented-intelligence"><em>Augmented Intelligence</em></a> (aka Intelligence Amplification) where analytics enhance the decision making process of the user. Optimization can turn a good FPL player into a great one by highlighting the hidden information behind all the numbers and revealing solid moves for each GW.</p><p>I believe we’ll reach a point where thoroughly disregarding analytical methods will become a thing of the past.</p><p>Currently, I’m working on an experiment where I will provide these types of practical insights to even the most seasoned FPL veterans. It will be an interesting exercise as it will give me the opportunity to peek into how successful managers think of possible player combinations while allowing them to to see what’s hidden beneath the prediction data.</p><h3>Closing note</h3><p>I truly enjoyed my first year of FPL and the opportunity to clarify many of the misconceptions towards optimization. I cannot wait until the new season starts on August 13 to collect more data in order to improve my analytical models, beat Bas (and others), and claim the SAS mini-league title (and maybe even win the goody bag myself or help others to win it)!</p><p>I’m sure it will be a great year as I’ll have a chance to apply my full model from the beginning, but this time using my experience from my first season to fine-tune certain things. My perception of FPL being too easy has certainly changed and it fuelled my addiction for building better tools for both myself and community.</p><p>If you are wondering, I finished last season with 2315 points and a rank of 304,304. That is the benchmark for years to come for myself as it is the rank I achieved while only relying on an analytical model.</p><blockquote><em>I wasn’t sure what to expect at the beginning, but finished 1st season of </em><a href="https://twitter.com/hashtag/FPL?src=hash&amp;ref_src=twsrc%5Etfw"><em>#FPL</em></a><em> with 2315 points, 304,304 overall rank (within 4%). Produced 7 tutorials on optimization, wrote 4 blog posts &amp; built an open-source webpage with several tools. It was fun, let’s try again next season! </em><a href="https://t.co/UOqWT5OZJ0"><em>https://t.co/UOqWT5OZJ0</em></a><em> </em><a href="https://t.co/NwtFMaaoSW"><em>pic.twitter.com/NwtFMaaoSW</em></a></blockquote><blockquote><em>- Sertalp B. Çay (@sertalpbilal) </em><a href="https://twitter.com/sertalpbilal/status/1396615571278532617?ref_src=twsrc%5Etfw"><em>May 23, 2021</em></a></blockquote><p><em>Originally published at </em><a href="https://alpscode.com/blog/fpl-reflections/"><em>https://alpscode.com</em></a><em> on July 26, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=693fc8237543" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Venue Optimization after the lockdown: Update and demo]]></title>
            <link>https://medium.com/@alpscode/venue-optimization-after-the-lockdown-update-and-demo-f421ef64c314?source=rss-bfd06ac27c77------2</link>
            <guid isPermaLink="false">https://medium.com/p/f421ef64c314</guid>
            <category><![CDATA[sports-management]]></category>
            <category><![CDATA[sports-analytics]]></category>
            <category><![CDATA[covid19]]></category>
            <category><![CDATA[sports]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[AlpsCode]]></dc:creator>
            <pubDate>Thu, 16 Jul 2020 13:46:45 GMT</pubDate>
            <atom:updated>2020-07-16T13:46:45.660Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SNgQa2f8XNft2GT8NsBOrA.png" /></figure><p>Back in May, we published a blog post about our optimization analysis to help venues decide how to allocate tickets while respecting social distancing guidelines. It received a lot of interest and with this new article we aim to provide an update in the light of changes to both the conditions and our solution.</p><p><strong>External conditions</strong></p><p>Many countries around the globe have been slowly moving out of the lockdown. Several sports leagues in Europe have restarted, albeit still in empty venues, including football (soccer) leagues in Germany, Italy, Spain and England. In the United States a few sports leagues have started back up and more should follow in the coming month including MLB, NBA, and NHL.</p><p>Several events have reached new records in terms of tv audience, but unfortunately they are still not allowed a live audience. This could change in the near future, but policies and guidelines remain very different between countries. For example, in France it was announced that venues could start accepting an audience of no more than 5000 spectators, irrespective of venue size. In the Netherlands, fans will be allowed back into stadiums when the football league restarts, as long as the venue can maintain 1.5m social distancing. This means that audience numbers will vary with the size of the venue. In the United States the recommended distance between groupings of people remains at 6 feet.</p><p><strong>SAS Venue Optimization</strong></p><p>SAS Venue Optimization may help (sports) organizations and governments to optimize venue capacity while adhering to local safety regulations. The solution provides an optimized layout of a venue based on a set of parameters and objectives entered by the user. For example, you can choose the distance to be maintained between people and/or the maximum group size of people sitting together. <strong>This can result in big differences</strong>. Our analysis showed that if people are allowed to sit on single seats and keep 1.5m between them, only about 15% of venue capacity could be used. However, if the maximum group size goes up to four, the ‘utilization rate’ rises to 30%.</p><p><strong>This tool is therefore very helpful for venues and (sports) organizations, enabling them to quickly run simulations to see how to maximize their ticket sales and total revenue</strong>. This is an important element for the financial survival of those organizations. We have added a new feature that gives the user the choice to optimize based on maximum number of people or maximum revenue. Users will need to provide ticket prices for all the seats, which can then be used by the optimization model to look for the seat allocation plan giving the most revenue.</p><p>The solution is also extremely <strong>flexible</strong>. The optimization parameters can be changed using different input levers. This means that it can be updated as safety guidelines change. Users can easily and quickly rerun the optimization and find suitable new seating plans when guidelines are updated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-fzMk8AY8G9pNKkdsqNWZg.png" /></figure><p><strong>“Eye-opening”</strong></p><p>We have demonstrated this solution to many customers and prospects now, and the first reaction we tend to get is <strong>‘it’s eye-opening’.</strong> People talk about keeping their distance, but often do not realize how this will look in practice. The visualization provided by our tool immediately shows the impact of particular guidelines on the available capacity of a venue and how the seats need to be occupied to maximize revenue.</p><p>Of course there are still concerns about how seating plans will work in real life. The situation looks good as long as everyone stays seated, but what if they don’t? As soon as people get up and start moving around, they will enter the ‘safety zones’ of those around them. We have therefore added another new feature to the solution to allow venues to leave aisle entrances and exits open. This allows people to reach or leave their seats without crossing anyone else’s safety zone. However, this significantly reduces the numbers of seats that can be used.</p><p>The image below shows the difference that this parameter can make. The left side shows the section lay-out optimized without considering the entry and exit paths (the red arrows show blocking points on paths). The right shows the lay-out leaving those paths open (the green arrow shows a clear path).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aZcxDHy6Ckl7u9ffD2Gq6g.png" /></figure><p><strong>Take a look yourself</strong></p><p>You can now take a look at our new solution. We’ve made a <strong>demo video</strong> available <a href="https://video.sas.com/sharing?videoId=6171846274001">which you can reach <strong>via this link</strong>.</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayers.brightcove.net%2Fpages%2Fv1%2Findex.html%3FaccountId%3D1872491364001%26playerId%3Ddefault%26videoId%3D6171846274001%26mode%3Diframe&amp;display_name=Brightcove&amp;url=https%3A%2F%2Fvideo.sas.com%2Fsharing%3FvideoId%3D6171846274001&amp;image=https%3A%2F%2Fcf-images.us-east-1.prod.boltdns.net%2Fv1%2Fstatic%2F1872491364001%2F0a18c726-8193-4eba-a071-e5dd6641fe4b%2Fab609eb5-2203-4eca-8b2a-d14b918f468d%2F1280x720%2Fmatch%2Fimage.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=brightcove" width="480" height="270" frameborder="0" scrolling="no"><a href="https://medium.com/media/54e1783e1762bc54a650b4746595639d/href">https://medium.com/media/54e1783e1762bc54a650b4746595639d/href</a></iframe><p>The venue used is the Carter-Finley Stadium of the <strong>NC State</strong> Wolfpack (American) college football team. It has a maximum capacity of 57,600 seats. We’d like to thank Colin Hargis of the team at NC State for allowing us to use their stadium for the demo.</p><p>In the video, after <strong>Bas Belfi</strong>’s introduction, I talk about and show the different features of the solution. Please send us your feedback and thoughts, either as comment or DM. We’d like to know what you think!</p><p><em>Project credits</em></p><p><em>This article, video and analysis are the result of the work done by the following team of people at SAS (in alphabetical order): Dan Axman, Bas Belfi, Christer Bodell, Sertalp B. Cay, Reece Clifford, Jay King, Luca Spinelli.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f421ef64c314" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sports after lockdown: optimizing seating solutions in stadiums]]></title>
            <link>https://medium.com/@alpscode/sports-after-lockdown-optimizing-seating-solutions-in-stadiums-9a213e45abcb?source=rss-bfd06ac27c77------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a213e45abcb</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[sports]]></category>
            <category><![CDATA[surveys]]></category>
            <category><![CDATA[analytics]]></category>
            <dc:creator><![CDATA[AlpsCode]]></dc:creator>
            <pubDate>Wed, 20 May 2020 13:16:20 GMT</pubDate>
            <atom:updated>2020-05-20T13:16:20.091Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*2FNbwO4sYLDT5jLNLGVvRw.png" /></figure><p>COVID-19 is having a big impact on us all. Work has changed enormously but the pandemic has also had a huge effect on our leisure time. Sporting events, live concerts and theatre have been particularly affected and the economic consequences on these industries are massive.</p><p>It is not surprising that professional sports organizations and performing arts venues are already starting to talk about what might be possible after the lockdown. Ticket revenues are a huge part of their income, and many of their financial models are built on the assumption that they will be able to sell 80% to 90% of their seating capacity for every event. Because of social distancing requirements, this is certainly not going to be an option in the near future.</p><h3>Solutions to social distancing</h3><p>One short term solution could be to host events in empty venues. The German Bundesliga, for example, has chosen this option, so that teams can at least finish the 2019–20 season. However, other clubs have suggested that any victory might feel a bit hollow without the fans there to celebrate with the players.</p><p>It might also be possible to apply social distancing inside venues. The general advice is to stay 2 metres or 6 feet apart. This would allow clubs to have some spectators present and bring in some much-needed revenue. But how could it be managed (and will it be enough)?</p><p>Using analytics, it is possible to find the ‘optimal’ seating solution under particular circumstances. In other words, you can maximize the number of spectators, but keep an acceptable distance between them. For example, let’s look at a simple grid of 7 rows by 7 seats, and the constraint that we need two empty seats separating people in each grouping. The ‘optimized’ solution (below) gives a maximum of 10 people fitting into an area that would normally seat 49.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*6gnXiqBd75neMYVNW6oapQ.png" /></figure><h3>Increasing the complexity</h3><p>We can also add more parameters. For example, people from the same household might go together — and then they could also sit together. The model can also be adapted to fit different guidelines on distance. <br>We tried this out on a real case: a section in an actual NFL stadium with a seating grid of 22 rows and 21 columns. We looked for the optimal solution in which tickets could be sold in groups of one, two, three or four. In this case the best option results in 132 out of 439 seats filled, or a utilization rate of 30%. You will see from the diagram below most people need to be in groups of two, or fours to achieve this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*03kK5aAzuBCVhkBrGO3CAw.png" /><figcaption>Image: actual seating section of 21 columns and 22 rows. The seats marked in green are the ones utilized when allocated in the most optimal way. The purple circles are the ‘safety zones’ (in this case a distance of 4 empty seats, or 6.3 feet / 1.9 meters) for each group of utilized seats. The circle marked in yellow is the ‘safety zone’ for the individual person sitting in the purple seat, row 12, column 14.</figcaption></figure><h3>Questions and concerns</h3><p>This analysis is still quite simplified, optimizing single sections only. We could use the results though to extrapolate it to entire entertainment venues. For example, by applying the 30% utilization rate we found above, the famous Nou Camp stadium in Barcelona with a capacity of almost 100,000 people could accept approximately 30,000 people while respecting the social distancing measures. A smaller scale example — but no less famous — could be Anfield, home of Liverpool FC with a maximum capacity of 54,000 people. Here it would mean 16,200 fans could attend. This could be significant not just in terms of matchday revenue, but also atmosphere. But again, the question is, is it enough?</p><p>These are only estimations of course, based on the extrapolation of the results of our simplified examples. Our model certainly could also provide exact calculations per venue, using detailed grid and layout information if made available (e.g. aisle, seat, row dimensions).</p><p>From the simplified analysis we can already see that there are a number of questions that need to be addressed:</p><p>First, the issue of static versus dynamic scenarios. This analysis is a static case: it assumes that everyone is seated at all times. But how do we manage people entering and leaving? And what if someone needs to get up in the middle of the game, for example? These are all questions that need to be considered. Solutions might include staggered arrival and departure times and one-way systems for moving around. Analytics and optimization can also be used to help answer some of these questions.</p><p>What about the economic impact? Perhaps any occupancy is better than none, but a 30% attendance is unlikely to cover the costs of many sports and entertainment organizations.</p><h3>Optimizing our way out of lockdown</h3><p>Analytics, and particularly optimization, can certainly help sports organizations and other entertainment venues to find the best seating arrangements to fit social distancing measures. Models can be used to show which seats to sell for groups of particular sizes. These solutions could also be used by transport operators to work out the social distancing capacity of buses, trains and trams — and to show people where to sit and stand to make the best use of the space. The same could be said for education and safely spacing out students in a classroom, or lecture hall.</p><p>As we move beyond lockdown, these analytics options are likely to be helpful in giving everyone a more scientific view of how to use our shared spaces, while still staying safe.</p><p>Are you involved in a club (or theatre, concert hall, or other venue) that is facing these issues and dilemmas? Reach out to us, we’d be happy to understand more and see if we can help. Or, take a moment to help us collect industry feedback on this topic, via <a href="https://sas.qualtrics.com/jfe/form/SV_6AvAKkz7fqSGVRr"><strong>this short survey</strong></a>.</p><p><strong>Project credits</strong></p><p>This blog and analysis are the result of the work done by the following team of people at SAS (in alphabetical order): Dan Axman, Bas Belfi, Christer Bodell, Sertalp Cay (me!), Reece Clifford, Jay King, and Luca Spinelli.</p><p><strong>Github</strong></p><p>If you want to understand how this analysis was done, you can find all details <a href="https://nbviewer.jupyter.org/github/sassoftware/sasoptpy/blob/develop/examples/notebooks/SeatingOptimization.ipynb">on Github.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a213e45abcb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Linux on Windows]]></title>
            <link>https://medium.com/@alpscode/using-linux-on-windows-8c0dd48d6e8?source=rss-bfd06ac27c77------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c0dd48d6e8</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[wsl]]></category>
            <dc:creator><![CDATA[AlpsCode]]></dc:creator>
            <pubDate>Sat, 05 Jan 2019 20:24:39 GMT</pubDate>
            <atom:updated>2019-01-05T20:24:39.299Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*tDHWePUIZMW1eFy1OYo6eA.jpeg" /><figcaption>Photo by Shane Aldendorff from Pexels</figcaption></figure><p>Linux is arguably the most developer-friendly operating system. From automation to feature-rich text editors, I see Linux as a must for any programmer. Powerful and hackable Linux ecosystem and the huge community make finding solutions to common problems very trivial.</p><p>If you need to use Windows for a variety of reasons, you are not out of options when it comes to using Linux. Over the years, I have tried a lot of different ways to enable Linux functionality on Windows, some are better than others but all of them have specific use cases. Windows 10 started supporting Linux subsystem natively a while ago which is called Windows Subsystem for Linux (WSL). WSL basically enables you to run Linux executables on Windows 10, natively. In this blog post, I will show how you can enable the Linux subsystem support on Windows 10, install Ubuntu and do some customization without an arm and a leg.</p><h3>Alternatives</h3><p>Before I start, let me point out two different methods that you can use instead of WSL.</p><ul><li><em>Cygwin</em> is a tool that provides Linux-like functionalities on Windows. It is an emulator hence there are lots of restrictions, but it is my to-go choice for basic Linux functionalities.</li><li><em>VirtualBox</em>, <em>VMWare Workstation</em> and similar programs help you to run a guest operating system on your machine (host). They often provide more functionalities than other alternatives, since you actually run an actual OS on your machine. For example, you can easily use a graphical user interface with them or make them boot with your system. I use VirtualBox for my home server (TeamSpeak, Dokuwiki, etc..) for quite some time and am very happy with its reliability so far. But I find WSL to be enough for most of my programming work.</li></ul><p>The real advantage of using WSL is to access Linux functionality without paying the cost of hosting a full OS which uses lots of resources to make it happen.</p><p>Installing WSL is very, very easy.</p><p>Right-click on Windows Start button and choose Windows PowerShell (Admin).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/195/0*GZVua3MgzEqU2z-4.png" /></figure><p>In PowerShell, simply run the following command:</p><pre>Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*wEWcpHfVnS0wdukC.png" /></figure><p>Voila! You have enabled WSL on your system. You may need to restart your PC at this point.</p><p>Now, it’s time to install a Linux version.</p><h3>Installing Linux Distributions</h3><p>You can download Ubuntu from Microsoft Store. Simply type Microsoft Store on your Start Menu and search for the Linux distribution of your choice such as <a href="https://www.microsoft.com/store/productId/9NBLGGH4MSV6">Ubuntu</a>.</p><p>If you prefer command line, use PowerShell in admin mode and run the following code. This command will download the Ubuntu from Microsoft Store and then run the installer.</p><pre>Invoke-WebRequest -Uri https://aka.ms/wsl-ubuntu-1804 -OutFile Linux.appx -UseBasicParsing; .\Linux.appx</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*14mVwKXzy33DelBh.png" /></figure><p>Replace -Uri parameter with Linux distribution of your choice. A list of Linux distros are available at <a href="https://docs.microsoft.com/en-us/windows/wsl/install-manual#downloading-distros">Microsoft’s website</a>. Here is a list of available distros as of writing this post:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a47593ac2f5798dd463b82f357c2339/href">https://medium.com/media/8a47593ac2f5798dd463b82f357c2339/href</a></iframe><p>You will instantly see the Linux console opens after the installation. It will ask you for a username and a password. Linux console will open with this default username from now on. The password is only asked when you want to perform an admin (sudo) command.</p><p>Now you should have a Linux terminal on your Windows machine. How cool is that? Before you dive into the Linux ocean, I have some quick tips for you below.</p><h3>Tips and further settings</h3><p>I have installed Ubuntu on my machine, so some of the settings might differ if you are using a different distro.</p><p>After the installation, you should be able to search Ubuntu on your Start Menu and see the icon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/0*-ZAeq5OZ_NusLeJR.png" /></figure><h3>Terminal colors</h3><p>Probably the most difficult step you will face today is changing the terminal colors. Default terminal colors are just.. ugly. Changing them to popular choices like Solarized, Monokai, or default Ubuntu terminal colors requires some heavy lifting.</p><p>James Garijo-Garde <a href="https://medium.com/@jgarijogarde/make-bash-on-ubuntu-on-windows-10-look-like-the-ubuntu-terminal-f7566008c5c2">wrote about changing WSL colors to default Ubuntu colors</a>. You essentially need to change 16 colors on the Properties menu one by one.</p><p>If you want, you can use a regedit file to import colors at once into your Registry. The tricky part is that your Ubuntu might be at a different location. Therefore, you need to change a setting to create a Registry entry, and use the name of the console. Here are the four steps you need to follow:</p><ol><li>Go to Properties menu, Colors tab and change a single color –does not matter which one– and save it. <br>(This step will make sure that you have a Registry entry for the console)</li><li>Run the .reg file (link to the repository is below).</li><li>Go to Registry Editor (Windows + R, regedit) and navigate to HKEY_CURRENT_USER\Console</li><li>Copy name of your Ubuntu editor, delete the entry, and replace the name ReplaceNameWithUbuntu with the name you copied.</li></ol><p>See the gif below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*51NhOzY0X1lwszm9.gif" /><figcaption>Changing WSL terminal colors with default Ubuntu colors</figcaption></figure><p><a href="https://github.com/alpscode/notebooks/blob/master/linux-on-windows/UbuntuColors.reg">Registry file</a> is on my Github repository.</p><h3>Disabling the bell (beep) on Linux</h3><p>Tab completion beep on Linux terminal is one of the most annoying sound known to humankind. Although it serves a purpose, you may soon get irritated during long working sessions or listening your favorite workout mix in the background.</p><p>You need to open /etc/inputrc file and uncomment the line set bell-style none.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/0*8sNLLxvTNvyCyqch.png" /></figure><p>After uncommenting the line, restart the terminal and you will no longer hear the beep sound.</p><h3>Increasing the buffer size</h3><p>If you right click on the title bar and click Properties you may further customize your terminal. One thing that you will find valuable is to increase the buffer size, so that you can scroll back to your recent commands and output. Go to Layout tab and change the Heightvalue under the Screen Buffer Size settings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/0*VTfgmiTj99r6y97l.png" /></figure><p>Also enable QuickEdit mode option under the Options tab to be able to copy text by selecting them and right-clicking.</p><h3>Accessing the Windows username</h3><p>You have <a href="https://docs.microsoft.com/en-us/windows/wsl/interop">access to Windows Command Line</a> using cmd.exe command even if you are working inside the Linux terminal. Using cmd.exe you can do lots of things, like accessing the Windows username. Adding</p><pre>export USERNAME=&quot;cmd.exe /c echo %USERNAME%&quot;</pre><p>to your .bashrc file enables $USERNAME variable on Linux terminal. Accessing the Windows username may come handy when writing scripts.</p><h3>Changing the username</h3><p>If you need to change the default username when you open the Ubuntu terminal, use</p><pre>ubuntu config --default-user new_username</pre><p>on PowerShell as an admin.</p><h3>Accessing Windows folders</h3><p>Your Windows folders should be accessible under /mnt folder. Simply navigate to your desktop using</p><pre>cd /mnt/c/Users/your-username/Desktop/</pre><h3>Creating a shortcut</h3><p>Windows does not provide an option for creating a shortcut when you right-click on store apps on Windows 10. The trick is to find the app on Start Menu and simply drag the app and drop it on the desktop.</p><h3>End</h3><p>So, that’s all folks. I hope you are happy with your brand new Linux terminal. Leave a reply below (or make a merge request) if you have a useful tip on mind that can be added here.</p><p>Happy new year!</p><h3>Resources</h3><ul><li><a href="https://docs.microsoft.com/en-us/windows/wsl/interop">WSL interoperability with Windows</a></li><li><a href="https://superuser.com/a/1266977">SuperUser Q/A for changing the default user</a></li><li><a href="https://www.reddit.com/r/bashonubuntuonwindows/">Reddit community for Bash on Ubuntu on Windows</a></li><li><a href="https://www.microsoft.com/store/productId/9NBLGGH4MSV6">Ubuntu on Windows Store</a></li></ul><p><em>Originally published at </em><a href="https://alpscode.com/blog/linux-on-windows/"><em>https://alpscode.com/blog/linux-on-windows/</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c0dd48d6e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing scripts with Reddit API]]></title>
            <link>https://levelup.gitconnected.com/writing-scripts-with-reddit-api-3f880aa0b974?source=rss-bfd06ac27c77------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f880aa0b974</guid>
            <category><![CDATA[reddit]]></category>
            <category><![CDATA[script]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[json]]></category>
            <dc:creator><![CDATA[AlpsCode]]></dc:creator>
            <pubDate>Wed, 26 Dec 2018 11:24:45 GMT</pubDate>
            <atom:updated>2018-12-27T01:48:23.597Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*HEKKfXM6q1TIMCIYnaDLLA.jpeg" /></figure><p>In this post, I will show how you can use Python to gather content and create a simple web page around it. See <a href="https://alpscode.com/blog/how-to-use-reddit-api/">the first part</a> to learn how to register an app to Reddit API and get started.</p><h3>Setup</h3><p>I often use PyCharm or Jupyter notebook for Python, but any Python environment will do the trick. You need to have a Reddit app id and app secret already at hand for this part. A basic knowledge of HTML and CSS might be useful, but not required for the high level content.</p><p>I will write a script which will search “puppy” related subreddits and show their top posts as a gallery. This project might be enough to trigger your <a href="https://en.wikipedia.org/wiki/Cute_aggression">cute aggression</a> if you are into dogs.</p><h3>Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*EqwPsTL77vsCrzSI.jpeg" /></figure><p>I have shown a basic introduction to Reddit API in the previous part. There are the steps I will follows:</p><ol><li>Find subreddits related to puppies<br> <a href="https://www.reddit.com/dev/api#GET_search">GET /subreddits/search</a></li><li>Get list of posts for every subreddit<br> <a href="https://www.reddit.com/dev/api#GET_top">GET /top</a></li><li>Filter and collect image links as an HTML code</li><li>Finally, display (and save) the HTML content</li></ol><p>GET requests are passive members of the RESTful APIs. So, the script won’t publish anything, but instead will return the content that you can parse.</p><p>The first order of business is to get subreddit names that you need to parse. You can use Reddit’s search function through the API:</p><pre>payload = {&#39;q&#39;: &#39;puppies&#39;, &#39;limit&#39;: 5}<br>response = requests.get(api_url + &#39;/subreddits/search&#39;, headers=headers, params=payload)<br>js = response.json()</pre><p>The variable js is a nested dictionary, which includes the response we got from Reddit. We can see the keys of the dictionary</p><pre>print(js.keys())</pre><pre>dict_keys([&#39;kind&#39;, &#39;data&#39;])</pre><p>You can get familiar with the responses, but visualizing it helps immensely. Using your favorite JSON viewer (<a href="https://jsoneditoronline.org/">https://jsoneditoronline.org/</a>, <a href="https://codebeautify.org/jsonviewer">https://codebeautify.org/jsonviewer</a>, <a href="http://jsonviewer.stack.hu/">http://jsonviewer.stack.hu/</a>) copy the content response.text to visualize the JSON response.</p><p>Reddit’s response include two objects. The object kind shows, well, what kind of data that data object has. If it is a listing, then the data object includes two strings, before and after which will be used to navigate. After we finish parsing the first page, for example, we will use the after parameter to request the second page.</p><pre>{<br>  &quot;kind&quot;: &quot;Listing&quot;,<br>  &quot;data&quot;: {<br>    &quot;modhash&quot;: null,<br>    &quot;dist&quot;: 5,<br>    &quot;children&quot;: [...],<br>    &quot;after&quot;: &quot;t5_2tjl7&quot;,<br>    &quot;before&quot;: null<br>  }<br>}</pre><p>Here, the data you can use is inside the children array. Reddit makes our lives easy here by giving us how many elements the children array has &quot;dist&quot;: 5. Let’s see what the first child includes:</p><pre>&quot;children&quot;: [<br>      {<br>        &quot;kind&quot;: &quot;t5&quot;,<br>        &quot;data&quot;: {<br>          &quot;display_name&quot;: &quot;puppies&quot;,<br>          &quot;display_name_prefixed&quot;: &quot;r/puppies&quot;,<br>          ...<br>        }<br>      },<br>      ...<br>]</pre><p>The data object has a lot fields. I will only use display_name in this step. A JSON viewer shows that the display_name can be accessed using the following breadcrumbs: data &gt; children &gt; i &gt; data &gt; display_name. Now you can gather all subreddit names as follows:</p><pre>sr = []<br>for i in range(js[&#39;data&#39;][&#39;dist&#39;]):<br>    sr.append(js[&#39;data&#39;][&#39;children&#39;][i][&#39;data&#39;][&#39;display_name&#39;])<br><br>print(sr)</pre><pre>[&#39;puppies&#39;, &#39;aww&#39;, &#39;dogpictures&#39;, &#39;corgi&#39;, &#39;lookatmydog&#39;]</pre><h3>Collecting posts</h3><p>Now that we have a list of subreddits, let us continue with collecting top 5 images from subreddits in our pool.</p><p>For this purpose, we will get top posts of all time from this subreddit. Remember that, some subreddits and their top posts may not be related to our search term, but our purpose here is to simply display a list of top posts from related subreddits.</p><p>The API request /r/(subreddit)/top – where subreddit will be replaced with the subreddit name – will give us the top posts. Simply replace subreddit with the subreddit names you stored in sr variable.</p><p>Before going any further, print a simple response to understand the structure:</p><pre>payload = {&#39;t&#39;: &#39;all&#39;}<br>r = requests.get(api_url + &#39;/r/puppies/top&#39;, headers=headers, params=payload)<br>print(r.text)</pre><pre>{<br>  &quot;kind&quot;: &quot;Listing&quot;,<br>  &quot;data&quot;: {<br>    &quot;modhash&quot;: null,<br>    &quot;dist&quot;: 25,<br>    &quot;children&quot;: [<br>      {<br>        &quot;kind&quot;: &quot;t3&quot;,<br>        &quot;data&quot;: {<br>          &quot;title&quot;: &quot;Recently at the airport&quot;,<br>          &quot;url&quot;: &quot;<a href="http://imgur.com/qPjptrd.jpg">http://imgur.com/qPjptrd.jpg</a>&quot;,<br>          &quot;thumbnail&quot;: &quot;<a href="https://b.thumbs.redditmedia.com/bJxCSi2BHocxt0RlUvfk2ibVIKhpniqFL7_j-sCEs-Y.jpg">https://b.thumbs.redditmedia.com/bJxCSi2BHocxt0RlUvfk2ibVIKhpniqFL7_j-sCEs-Y.jpg</a>&quot;,<br>          &quot;approved_at_utc&quot;: null,<br>          &quot;subreddit&quot;: &quot;puppies&quot;,<br>          &quot;selftext&quot;: &quot;&quot;,<br>          ...<br>        }<br>      },<br>      ...<br>    ],<br>    &quot;after&quot;: &quot;t3_7s49s5&quot;,<br>    &quot;before&quot;: null<br>  }<br>}</pre><p>As you see from the JSON response, you need to access the data in this order: data &gt; children &gt; i &gt; data &gt; title. I will only use title, thumbnail and url here, but it is a good idea to check what kind of data Reddit returns for future projects.</p><p>You can iterate over all children and save the thumbnails inside an HTML code. This HTML code can be printed if you are using Jupyter. I will also show how it can be saved as an HTML page. If you are not familiar with HTML, perhaps it is a good idea to check the basics at your earliest convenience, as it is a very useful skill especially nowadays. The HTML tags I use following are as follows:</p><ul><li>h3 for printing titles</li><li>div for grouping and styling</li><li>span for grouping HTML elements together</li><li>a for creating links</li><li>img for displaying images</li></ul><p>The following code shows the title of the subreddit, and then puts 5 top images next to each other. It’s a good idea to use thumbnails instead of full images since you only need to show a small photo in the gallery. When user hovers, it will show the original poster’s title and clicking will take user to the full image (or URL).</p><pre>payload = {&#39;t&#39;: &#39;all&#39;, &#39;limit&#39;: 5}<br>imghtml = &#39;&#39;<br>for s in sr:<br>    imghtml += &#39;&lt;h3 style=&quot;clear:both&quot;&gt;{}&lt;/h3&gt;&lt;div&gt;&#39;.format(s)<br>    r = requests.get(api_url + &#39;/r/{}/top&#39;.format(s), headers=headers, params=payload)<br>    js = r.json()<br>    for i in range(js[&#39;data&#39;][&#39;dist&#39;]):<br>        if js[&#39;data&#39;][&#39;children&#39;][i][&#39;data&#39;][&#39;thumbnail&#39;] == &#39;&#39;:<br>            continue<br>        imghtml += &#39;&lt;span style=&quot;float:left&quot;&gt;&lt;a href=&quot;{}&quot;&gt;&lt;img src=&quot;{}&quot; title=&quot;{}&quot; target=&quot;_blank&quot; \&gt;&lt;/a&gt;&lt;/span&gt;&#39;.format(<br>            js[&#39;data&#39;][&#39;children&#39;][i][&#39;data&#39;][&#39;url&#39;],<br>            js[&#39;data&#39;][&#39;children&#39;][i][&#39;data&#39;][&#39;thumbnail&#39;],<br>            js[&#39;data&#39;][&#39;children&#39;][i][&#39;data&#39;][&#39;title&#39;],<br>        )<br>    imghtml += &#39;&lt;/div&gt;&#39;</pre><p>Here, the GET request to /r/(subreddit)/top returns the top posts from that subreddit. I passed time period t=all and a limit on number of posts from each subreddit limit=5 for the query. At the end imghtml should have the HTML code you need to display.</p><h3>Result</h3><p>We have arrived the final step of our short and hopefully to-the-point tutorial. Images can be displayed in Jupyter notebook as follows:</p><pre>from IPython.core.display import display, HTML<br>display(HTML(imghtml))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/0*5PaH9ZwPjr0d0yFn.png" /></figure><p>The functions we used display and HTML are specific to Jupyter. If you are using a different tool to write your Python code, it makes sense to write the HTML code into a page.</p><pre>with open(&quot;puppies.html&quot;, &quot;w&quot;, encoding=&#39;utf-8&#39;) as html_page:<br>    html_page.write(imghtml)</pre><p>Now, you can navigate the folder your Python code lives and open the appropriately named puppies.html page. See <a href="http://htmlpreview.github.io/?https://github.com/alpscode/notebooks/blob/master/reddit-api/puppies.html">a preview here</a>.</p><h3>Closing</h3><p>There is a ton of information that I could not covered in here to keep this post to the point. I was hoping to write a trivia game, where you see a photo and try to guess the subreddit it was shared, but I have to skip it for now. I might do it in another iteration, hopefully.</p><p>If you have enjoyed the tutorial check my <a href="https://nbviewer.jupyter.org/github/alpscode/notebooks/blob/master/reddit-api/Reddit-to-Webpage.ipynb">Jupyter notebook</a> to see a full example, where a web page is generated out of a given search query. In one of the upcoming blog posts, I will show you how to write a Reddit bot, that will parse information from two separate APIs and post comments on Reddit.</p><h3>References</h3><ul><li><a href="https://nbviewer.jupyter.org/github/alpscode/notebooks/blob/master/reddit-api/RedditAPI-2.ipynb">Part 2 notebook</a></li><li><a href="https://nbviewer.jupyter.org/github/alpscode/notebooks/blob/master/reddit-api/Reddit-to-Webpage.ipynb">Reddit to Webpage notebook</a></li><li><a href="http://htmlpreview.github.io/?https://github.com/alpscode/notebooks/blob/master/reddit-api/puppies.html">An example output HTML page</a></li></ul><p><em>Originally published at </em><a href="https://alpscode.com/blog/scripting-with-reddit-api/"><em>https://alpscode.com/blog/scripting-with-reddit-api/</em></a><em>.</em></p><p><a href="https://gitconnected.com/learn/python">Learn Python - Best Python Tutorials (2019) | gitconnected</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f880aa0b974" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/writing-scripts-with-reddit-api-3f880aa0b974">Writing scripts with Reddit API</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use Reddit API]]></title>
            <link>https://medium.com/@alpscode/how-to-use-reddit-api-362474a34c80?source=rss-bfd06ac27c77------2</link>
            <guid isPermaLink="false">https://medium.com/p/362474a34c80</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[reddit]]></category>
            <category><![CDATA[script]]></category>
            <category><![CDATA[http-request]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[AlpsCode]]></dc:creator>
            <pubDate>Fri, 21 Dec 2018 20:40:57 GMT</pubDate>
            <atom:updated>2018-12-21T20:45:53.584Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*9qcNpkkGxfFm3CuyQAZy2g.jpeg" /></figure><p>One of the most valuable things I learned in recent years was learning how to use Public APIs to develop tools. An API (Application program interface) is a set of tools to communicate with another service. Learning how to use APIs is very valuable for web applications, but beyond that it is a useful skill to expand your horizon. Once you get the hang of it, there is endless possibilities what you can do with it.</p><p>The best way to learn something is actually trying it. Following this wisdom, we will develop a Reddit bot but I will split the blog posts into smaller, easier pieces. The whole point of this very first post is to understand how Reddit API works and how to get started.</p><h3>Setup</h3><p>Before I start doing any of the work, I would like to describe what I will use here. I will be doing the actual work on Python, since it is a great language for writing scripts and prototyping. At the end, I will share a Jupyter Notebook link if you would like to clone and use.</p><h3>Creating an app</h3><p>Almost all public APIs requires registration. This is partly due to tracking the usage and preventing users to abuse available resources.</p><p>Reddit’s registration is at this address after signing in: <a href="https://old.reddit.com/prefs/apps/">https://old.reddit.com/prefs/apps/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*gv_QH2bcG5Fgj7Vb.gif" /></figure><p>In this page, I only fill name puppy-parser app type script and redirect uri http://localhost:8080. Since my script will be working locally, I don’t need a redirect uri, but redirecting to localhost will work fine for our purposes.</p><p>After submitting the app details, we get a public key (right under the app name) and a secret key. This key pair is required to use the Reddit API. Based on which type of app you request, you may not get a secret key. The secret key, as the name suggests, should be secret. Only the user can hold on to this, as it will give access to the API itself.</p><h3>Getting an access token</h3><p>Reddit API requires users to obtain an access token before making queries. This token will tell the API server that we have authorization to reach information. Reddit (as of writing this post) uses OAuth2 authorization framework. It is very easy to use and I will demonstrate how to do it here.</p><p>The official Reddit API documentation is at <a href="https://old.reddit.com/dev/api/">https://old.reddit.com/dev/api/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*5cSBBmdGWGJSkyeY.jpg" /><figcaption><em>Access tokens are required to access Reddit API</em></figcaption></figure><p>Simply put, I will pass my Reddit username, password, app id and app secret to generate a token. This token will be user for the rest of our requests.</p><p>In Python, using the requests package (install it with pip install requests if you get an error) you can request an access token as follows:</p><pre>import requests<br>base_url = &#39;<a href="https://www.reddit.com/">https://www.reddit.com/</a>&#39;<br>data = {&#39;grant_type&#39;: &#39;password&#39;, &#39;username&#39;: REDDIT-USERNAME, &#39;password&#39;: REDDIT-PASSWORD}<br>auth = requests.auth.HTTPBasicAuth(APP-ID, APP-SECRET)<br>r = requests.post(base_url + &#39;api/v1/access_token&#39;,<br>                  data=data,<br>                  headers={&#39;user-agent&#39;: &#39;APP-NAME by REDDIT-USERNAME&#39;},<br>		  auth=auth)<br>d = r.json()</pre><p>At the end of this request the dictionary d should have a similar output to this one:</p><pre>{&#39;access_token&#39;: &#39;216912536673-vRVst4XgHf8SaYQrGlfWEd8zAOo&#39;, &#39;token_type&#39;: &#39;bearer&#39;, &#39;expires_in&#39;: 3600, &#39;scope&#39;: &#39;*&#39;}</pre><p>After obtaining the token, API requests should be made to https://oauth.reddit.com instead of https://www.reddit.com. Let’s see how we can access the user information:</p><pre>token = &#39;bearer &#39; + d[&#39;access_token&#39;]<br><br>base_url = &#39;<a href="https://oauth.reddit.com/">https://oauth.reddit.com</a>&#39;<br><br>headers = {&#39;Authorization&#39;: token, &#39;User-Agent&#39;: &#39;APP-NAME by REDDIT-USERNAME&#39;}<br>response = requests.get(base_url + &#39;/api/v1/me&#39;, headers=headers)<br><br>if response.status_code == 200:<br>    print(response.json()[&#39;name&#39;], response.json()[&#39;comment_karma&#39;])</pre><pre>alpscode 0</pre><p>It worked! Two things to note here:</p><ol><li>Instead of passing our password every time, only thing we need to use is the authentication token.</li><li>We add bearer in front of the token as a requirement. This is a common practice.</li></ol><p>You may have noticed earlier that each auth token expires after a while. The token is only valid for 1 hour. When it expires, we need to request a new token. Tracking the status code of the request helps to identify when the token expires.</p><pre>print(r.status_code)</pre><pre>200</pre><p>If the status_code is not 200 (which corresponds to OK in <a href="https://www.restapitutorial.com/httpstatuscodes.html">HTTP Response Codes</a>), then the token needs to be refreshed. An invalid token will return 401 (Unauthorized) error code.</p><h3>Playing with the API</h3><p>Perhaps the best way to learn the API is to play with it. Reddit’s API documentation has almost everything there is to know.</p><p>Let us try to search for a keyword and list the obtained subreddits. The API says the url is subreddits/search with a few parameters. We will put puppies for the query string, and also a limit of 5 subreddits and sort by relevance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/0*FdVgqSZBO5nc1xKW.png" /><figcaption><em>Reddit API used in a Python HTTP request</em></figcaption></figure><pre>payload = {&#39;q&#39;: &#39;puppies&#39;, &#39;limit&#39;: 5, &#39;sort&#39;: &#39;relevance&#39;}<br>response = requests.get(api_url + &#39;/subreddits/search&#39;, headers=headers, params=payload)<br>print(response.status_code)</pre><p>The very first thing you need to check is always whether the request type is GET or POST. Then, check the url. Remember that the url is always added at the end of the base url, which is https://oauth.reddit.com in our case. Last, pass the parameters as a Python dictionary. You can see that the response code is 200, which means the query is alright. Let’s see the content.</p><p>In a typical API request, we can get the reply as a JSON object. There are various types, but JSON is almost an industry standard nowadays. Grab the content as follows:</p><pre>values = response.json()</pre><p>As far as JSON response of Reddit API is concerned, the response dictionary is usually very loaded. The first thing you can check is the dictionary keys. After the keys, we can grab the piece we want, and move progressively. An easy way if you are using a new request is to print the content using print(response.text)and copy it to <a href="https://jsonviewer.stack.hu/">https://jsonviewer.stack.hu</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/0*dYM-gy0w1qrm5er0.png" /></figure><p>We will see the details later, but we can print the list of subreddits as follows:</p><pre>for i in range(len(values[&#39;data&#39;][&#39;children&#39;])):<br>    print(values[&#39;data&#39;][&#39;children&#39;][i][&#39;data&#39;][&#39;display_name&#39;])</pre><pre>puppies<br>aww<br>dogpictures<br>corgi<br>lookatmydog</pre><p>You can find all the codes in my <a href="https://nbviewer.jupyter.org/github/alpscode/notebooks/blob/master/reddit-api/RedditAPI-1.ipynb">Jupyter notebook repository</a>.</p><h3>Next steps</h3><p>In the following post, we will create a Python script to parse posts from certain subreddits and show them as a gallery. For this step, we will investigate the Reddit API documentation in more detail and also create a simple web page.</p><h3>Resources</h3><ul><li><a href="https://github.com/reddit-archive/reddit/wiki/API">API overview</a></li><li><a href="https://www.reddit.com/dev/api">API documentation</a></li><li><a href="https://github.com/reddit-archive/reddit/wiki/OAuth2">OAuth2 details</a></li><li><a href="https://github.com/reddit-archive/reddit/wiki/OAuth2-Quick-Start-Example">Quick Start example</a></li></ul><p><em>Originally published at </em><a href="https://alpscode.com/blog/how-to-use-reddit-api/"><em>https://alpscode.com/blog/how-to-use-reddit-api/</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=362474a34c80" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>