teleren/devto huggingface dataset:
Converting an aware datetime object from one timezone to another in python
Tags: python, datetime, pytz
Published: 2019-10-15 12:13:25

## Problem
I recently ran into a beginner problem at work where I had to write a utility method that would receive a timestamp and the timezone of the timestamp and convert it into a human readable form for UTC timezone. Now, this looked straightforward except that I hadn't worked with the datetime library before. So after much searching, I came across the very useful `datetime.astimezone()` method which helped solve the problem.

## About the `datetime.astimezone(tz=None)` method
The `astimezone(tz=None)` takes in a **datetime** object and returns a new datetime object with the time set to the equivalent time in the **datetime.tzinfo** attribute **tz**. If no **tz** object is not provided, it defaults to **UTC** timezone.

```bash
>>> from datetime import datetime
>>> from pytz import timezone

# Convert the local time in London to the local time in Sydney
>>> datetime.now(timezone('Europe/London')).astimezone(timezone('Australia/Sydney'))
datetime.datetime(2019, 10, 15, 22, 48, 4, 449019, tzinfo=<DstTzInfo 'Australia/Sydney' AEDT+11:00:00 DST>)

# Convert the time in London to it's equivalent in UTC
>>> datetime.now(timezone('Europe/London')).astimezone()
datetime.datetime(2019, 10, 15, 11, 54, 58, 952388, tzinfo=datetime.timezone(datetime.timedelta(0), 'UTC'))
```

## Final Solution to my problem
Below is the solution I came up with which made use of the [datetime.astimezone()](https://docs.python.org/3/library/datetime.html) method in the datetime library. Note that the code has been simplified to allow the reader to grasp it more easily. 

```python
from datetime import datetime
from pytz import timezone

def change_timezone_of_datetime_object(date_time_object, new_timezone_name):
    """Return the *date_time_object* with it's timezone changed to *new_timezone_name*

    :param date_time_object: The datetime object whose timezone is to be changed
    :type date_time_object: datetime
    :param new_timezone_name: The name of the timezone to which the *date_time_object* is to be changed to
    :type new_timezone_name: str
    :rtype: datetime
    """
    # Create a pytz.timezone object for the new_timezone
    new_timezone_object = timezone(new_timezone_name)
    # Update the timezone of the datetime object
    date_time_object = date_time_object.astimezone(new_timezone_object)
    # Return the converted datetime object
    return date_time_object

# Testing
>>> dtobj = datetime.now(timezone('UTC'))
>>> change_timezone_of_datetime_object(dtobj, 'Europe/London')
datetime.datetime(2019, 10, 15, 13, 56, 30, 220369, tzinfo=<DstTzInfo 'Europe/London' BST+1:00:00 DST>)
```

## References
* [Python datetime library documentation](https://docs.python.org/3/library/datetime.html)
* [10 things you need to know about Date and Time in Python with datetime, pytz, dateutil & timedelta](https://medium.com/@eleroy/10-things-you-need-to-know-about-date-and-time-in-python-with-datetime-pytz-dateutil-timedelta-309bfbafb3f7) - Example 4 turned out to be very useful. Thanks [@eleroy](https://medium.com/@eleroy).
Lexical Scope System & How it works In JavaScript
Tags: javascript, react, reactnative
Published: 2019-10-15 12:02:17

![Scope](https://miro.medium.com/max/2100/0*nql_UCciXvKgm8PQ.jpeg)

What is Scope ?
=============

friend of Js Engine, that collects and maintains a look-up list of all the declared identifiers (variables), and enforces a strict set of rules as to how these are accessible to currently executing code.
What is Lexical Scope & How it Works ! ?
Lexical scope means that scope is defined by author-time decisions of
where functions are declared. The lexing phase of compilation is
essentially able to know where and how all identifiers are declared,
and thus predict how they will be looked-up during execution.

To visualize the process of nested Scope resolution, I want you to think of this tall building.
Let’s consider this block of code:

![Code_Snippet](https://miro.medium.com/max/1344/0*3fIDvhgVnRnxw2id.png)

Bubble 1️⃣ encompasses the global scope, and has just one identifier in it: foo.
Bubble 2️⃣ encompasses the scope of foo, which includes the three identifiers: a, bar and b..
Bubble 3️⃣ encompasses the scope of bar, and it includes just one identifier: c..


Scope bubbles are defined by where the blocks of scope are written, which one is nested inside the other, etc. let’s just assume that each function creates a new bubble of scope.
The bubble for bar is entirely contained within the bubble for foo, because (and only because) that's where we chose to define the function bar.
Notice that these nested bubbles are strictly nested. We’re not talking about Venn diagrams where the bubbles can cross boundaries. In other words, no bubble for some function can simultaneously exist (partially) inside two other outer scope bubbles, just as no function can partially be inside each of two parent functions.

![Code_Snippet](https://miro.medium.com/max/2284/0*i5AQWy0OIsBDERVO.png)

Here variable `b` will resolve lexically because javascript has lexical scope system💯
it does not matter where from where function is calling it only depends where it’s declared 👀
function `bar` is declared in foo scope but we are calling this function from foo1 scope 🙉

Conclusion!
===========


lexical scope is write-time.Lexical scope cares where a function was declared.
Python: To append or extend
Tags: python, computerscience
Published: 2019-10-15 11:46:23

I wrote a little tidbit this morning for my company, who is starting to roll out some Python-based services for the first time. We post little notes to help each other learn Python and to socialize the language in a shop that had only used Javascript previously.

I am up early looking at some `boto3` examples and stumbled across the `extend` method on the Python List object. Previously I had only used the `append` method. Also this behavior changed slightly from version 2.X to 3.7, so perhaps that's where my confusion stemmed. (Check out the version differences in the Python docs link below.)

When working with lists in Python 3.7, it's pretty common to want to add more elements into that list. A common way to do this is would be to use the append method. This may not actually produce the structure you intend and using the extend method may be more intuitive.

Let's say you have two lists and use the append method:

```
a = [1,2,3]
b = ['z', 'y', 'x']

a.append(b)
print(a)
# [1,2,3,['z', 'y', 'x']]
```

The entire list b is appended to list a.
Let's use the extend method:

```
a = [1,2,3]
b = ['z', 'y', 'x']

a.extend(b)
print(a)
# [1,2,3,'x','y','z']
```

This adds each element of the iterable list b to the end of list a.
https://docs.python.org/3.7/tutorial/datastructures.html

Apparently it is also shorthand for an assignment of slices, which is kinda cool too.
sell cookies in nursing homes not neighborhoods
Tags: product, marketing, efficiency, metaphors
Published: 2019-10-15 11:43:55

---
title: sell cookies in nursing homes not neighborhoods
series: metaphors
published: true
description: a metaphor about marketing
tags: product, marketing, efficiency, metaphors
cover_image: https://thepracticaldev.s3.amazonaws.com/i/vew4pwf3qokzgi72gscj.jpg
---

Sell your product to an aggregated common market, not a randomly dispersed one.  It is efficient to sell your message once to a room full of people who want your product. It is not as efficient to sell a few messages multiple times to people with little in common.  Especially when you consider the barriers (physical space/time) between them. 

*Where does your market congregate with the most density?*

<sub><sub>[Photo by Alex on Unsplash](https://unsplash.com/photos/7mh-czWZRsA)</sub></sub>
Top 7 Web Development Tips
Tags: webdev, tech, design, advice
Published: 2019-10-15 11:32:11

---
title: Top 7 Web Development Tips
published: true
description: Top Most Web Designing and Development Trends
tags: #webdev #tech #design #advice
---
Top trends for web design and development. How clients, customers and endeavor directors saw business forms, sites assume a huge job in setting up an association's computerized domain. 

###Full article source: https://decipherzone.com/blog-detail/web-design-development-trends

A site is increasingly similar to an online mirror mirroring each part of the organization. An expertly made business site goes about as an interface passing on your business thought to the entire world. The site speaks to the computerized arrangement of your business, which permits the potential leads and the clients to look through and gain proficiency with the brand story, comprehend its contributions, item determinations, and administrations.

#[Top Most Web Designing and Development Trends](https://decipherzone.com/blog-detail/web-design-development-trends)

Today, websites have surpassed as simply the virtual portrayal of an organization. It is vital to building an environment and brand, produce business, and gain a more extensive customer base. Notwithstanding making a solid impact on the guest, a website designed in the synchronize of most recent patterns keeps the brand ahead in the race of top positioning websites.

##Improving the visual factor

Sites, which are wealthy in appearance, charm the clients. Designers utilize different Graphical User Interface (GUI) choices, for example, eye-appealing shading blends, format and arrangement systems, gadgets, menus, and more to complement the components establishing to the look and feel of a site. The UI toolbox offers particular applications to include realistic and activity, improving the site.

##Adventurous Color Scheme 

###Full article source: https://decipherzone.com/blog-detail/web-design-development-trends
javascript question - Hoisting
Tags: javascript, beginners, interview
Published: 2019-10-15 11:15:48

What you think, will be the output of the following code ? 

<code>
hello();
console.log(a);
function hello(){
    console.log("Hello World!");
}
var a = 5;
console.log(a);
</code>


A small hint, the output of the above code snippet depends on : - 
<strong>Hoisting</strong> -  An interesting javascript concepts where <i>variable</i> and <i>function</i> declarations are allocated memory during context creation phase (phase 1) before execution

Javascript engine will start executing code line by line in the execution phase (phase 2) 

Cheers!
Why do code reviews?
Tags: codereviews, process
Published: 2019-10-15 11:00:53

I still remember the first time someone left me a comment in a code review. The disrespect, the audacity, how does anyone dare to criticize my perfect code?

For me it was a completely new experience to have someone else go through my code and tell me in detail what I should change. Fortunately, after going through the same thing a few times, I began to accept and understand the importance of code reviews, and I got used to my new life.

First of all, let's define: What is a code review? A code review is an activity in which one or more programmers examine another programmer's code. This is done in order to find problems of any kind at an early stage of the software development cycle.

Right now I can't imagine a project where code reviews are not performed, and the reasons are many. If your team doesn’t do code reviews, I hope these convince you to start.

1. No matter how much we want to believe it sometimes, we are not perfect. For that reason, having a group of engineers on your team check your code is extremely valuable. No matter how much you look at your own code, there are things you won't see just because you're too familiar with it. 

2. A code review is an opportunity to learn from the different backgrounds of your teammates. Even when everyone in your team is an excellent engineer, everyone has different strengths. Some can be very good at unit testing, others will be better at design and architecture, and others at following good coding practices. The point of teamwork is to complement one another’s abilities.

3. Even if your code is perfect functionality wise and has no bugs, another crucial aspect is that the code is readable and understandable by other people. Remember that your code will most likely be modified by someone else in the future, so it's helpful to know if other developers can "guess" what it does.

4. Code reviews are also learning opportunities for other members of your team. It is not only for others to give you recommendations on how to improve your code, but also for everyone to learn to identify problems in code, and of course, to learn from the things you do well.

5. Finally, a review helps everyone to become more familiar with the codebase, and keeps everyone aware of the changes that are made to different repositories day to day. It is also a good way to introduce new members to a project and help them become familiar with the source code.

I hope I have convinced you that code reviews are important, if not essential, to software quality. If your team is not doing them, bring up the idea, or better yet, show them this article! Who knows, you might change their mind.
Best practices for Kubernetes security; scaling write-heavy productions; & SRE
Tags: kubernetes, security, architecture, sre
Published: 2019-10-15 11:00:15

*My TL;DR style notes from articles I read today.*

### [9 Kubernetes security best practices everyone must follow](http://bit.ly/kubernetes-security)
 
1. Always use the latest stable version. 
2. Enable role-based access control (RBAC). Avoid granting cluster-wide permissions.
3. Make sure to create non-default namespaces with security boundaries customized by their workload.
4. Run especially sensitive workloads on a dedicated set of machines to limit fallout from any breaches.
5. Carefully secure access to cloud metadata.
6. Create and define cluster network policies.
7. Define a cluster-wide Pod Security Policy for how workloads may run in each cluster.
8. Harden node security by ensuring your host is secure & controlling network access to sensitive ports. 
9. Enable audit logs. Actively monitor them to identify access attempts.
 
*[Full post here](http://bit.ly/kubernetes-security), 5 mins read*

---

### [How Sqreen handles 50,000 requests every minute in a write-heavy environment](http://bit.ly/scale-architecture)

Three principles used by Sqreen to build this scalable architecture: 
- Caching to handle large volumes of requests.
- Using queues to reduce the number of write operations demanded within a given time frame to guard against overload. 
- Designing applications in a way that scalability is achieved by using more or fewer iterations of the same module to scale up and down, rather than requiring a single unit to work faster or harder.

*[Full post here](http://bit.ly/scale-architecture), 9 mins read* 

---

### [Site reliability engineering best practices for data pipelines](http://bit.ly/sre-practices)

- Define and measure service-level objectives (SLOs) to ensure data freshness, data correctness, and superior data isolation. 
- Plan for dependency failures by checking for overdependence on products that don’t meet their own SLOs. 
- Create and maintain system diagrams, process documentation and playbook entries that outline recovery from alert conditions. 
- Reduce hot-spotting by balancing out the workload across resources.
- Utilize autoscaling. 
- Adhere to strict access control for privacy, security and data integrity.
- Use idempotent and two-phase mutations to avoid duplication or storage of incorrect data in case of pipeline failure in the middle of a process.
- Use checkpointing to store partially implemented processes. 


*[Full post here](http://bit.ly/sre-practices), 5 mins read* 

---

*I share these TL;DR versions of articles on software engineering that I read every weekday through my newsletter - [in.snippets(). Sign up here](https://mailchi.mp/appsmith/insnippets?utm_source=devto&utm_medium=post08&utm_campaign=is) if you liked what you just read.*
Let's make #help great again
Tags: discuss, watercooler
Published: 2019-10-15 10:50:38

![meme](https://i.imgflip.com/3dcq7t.jpg)

The Dev mods have granted me moderation rights to [#help](https://dev.to/t/help), so I can try to keep the articles on-topic and provide a place that people can keep answers to their questions. 

So, to the people that use the tag to get help or answer questions, what can I/we do to make it better? 

How do we encourage more people to come to Dev to ask for help?
#SQL30 Day 13: Permutations
Tags: sql, database, postgres, challenge
Published: 2019-10-15 10:45:19

Welcome to the SQL showdown series!  

### What is this and how does it work?

I'm committing to publishing a SQL challenge every day for 30 days.  In each post I'll describe **my** solution to the last day's challenge.  I'll follow that up with a full description of the challenge for the next day.

Write your own solution in the comments!  Let's see who can come up with the most creative solutions.

### Challenge #13: Permutations

This is a seemingly simple, yet somewhat tricky challenge for today.

**Can you generate all of the permutations of a given set in SQL?**

There is no table available on the sandbox server for today's challenge, but the source data is easy to create using something like the [generate_series](https://www.citusdata.com/blog/2018/03/14/fun-with-sql-generate-sql/) function in PostgreSQL.

For this challenge I'm using the set {1, 2, 3}.  Here's an example of the output we should get:

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/4s82y6dkmfgce7xf7fvt.png)

### Solution to Challenge #12: Greatest Discount

The key trick to solving yesterday's challenge is to think in terms of events, rather than ranges of times.  In other words, a discount starting is an event, and a discount ending is an event.  When a discount starts the overall cumulative rate rises, and conversely, the rate falls when a discount ends.

To break down a range into separate events we can use **UNION ALL** to combine queries that select the start and end dates.

```sql
SELECT start_date AS dt, rate FROM day12.discount
UNION ALL
SELECT end_date AS dt, -rate FROM day12.discount
```

Negating the rate in the second query will allow us to do a running total on the rates, thus giving the cumulative rate at each point in time.  

Whenever a phrase like "running total" or "rolling average" appears, it's a safe bet that [window functions](https://dev.to/helenanders26/sql-301-why-you-need-sql-window-functions-part-1-6e1) are part of the solution.  Let's look at how we can combine the first query with a window function to find the cumulative discount rate:

```sql
SELECT sum(rate) OVER (ORDER BY dt) AS cumulative_disc, dts.dt FROM (
  SELECT start_date AS dt, rate FROM day12.discount
  UNION ALL
  SELECT end_date AS dt, -rate FROM day12.discount
) AS dts ORDER BY cumulative_disc DESC;
```

The **ORDER BY** within the **OVER** clause limits the sum to the current row and all rows prior to it (sorted by date).  From there it's just a matter of sorting the entire query to get the greatest possible discount.

### Good luck!

Have fun, and I can't wait to see what you come up with! I'll be back tomorrow with a solution to this problem and a new challenge.
Graph databases: which one?
Tags: help
Published: 2019-10-15 10:44:32

---
title: Graph databases: which one?
published: true
description: Experience with graph databases. Wanna share?
tags: help
---

I have been considering graph databases for a while. I have minor experience with Neo4j, but I am a total newbie about what alternatives are in the market.

I see Amazon has Neptune, there exists OrientDB, MongoDB has incorporated graph functions, ... 

Has anyone built a product on top of a graph database and would like to share how the experience was? Should I stick to Neo4j?
Sudo Flaw Lets Linux Users Run Commands As Root Even When They're Restricted
Tags: linux, security, infosec, cybersecurity
Published: 2019-10-15 10:41:50

---
title: "Sudo Flaw Lets Linux Users Run Commands As Root Even When They're Restricted"
cover_image: "https://thepracticaldev.s3.amazonaws.com/i/hyldd3r7l6omep26cbqd.png"
published: true
description: "The vulnerability in question is a sudo security policy bypass issue that could allow a malicious user or a program to execute arbitrary commands as root on a targeted Linux system even when the sudoers configuration explicitly disallows the root access."
tags: "linux,security,infosec,cybersecurity"
---

In [this article](https://thehackernews.com/2019/10/linux-sudo-run-as-root-flaw.html) we can read how Joe Vennix of Apple Information Security uncovered a security flaw on the `sudo` command, that allows a malicious user or application to run any command as the `root` user on a Linux system.

## TLDR

#### The security policy vulnerability

> The vulnerability in question is a sudo security policy bypass issue that could allow a malicious user or a program to execute arbitrary commands as root on a targeted Linux system even when the "sudoers configuration" explicitly disallows the root access.

#### How to exploit

> What's more interesting is that this flaw can be exploited by an attacker to run commands as root just by specifying the user ID "-1" or "4294967295."

> That's because the function which converts user id into its username incorrectly treats -1, or its unsigned equivalent 4294967295, as 0, which is always the user ID of root user.

#### Affected Sudo versions

> The vulnerability affects all Sudo versions prior to the latest released version 1.8.28, which has been released today, a few hours ago and would soon be rolled out as an update by various Linux distributions to their users.


## Conclusion

Never take security for granted, even the most important programs that are intended to secure your system may contain security vulnerabilities.

Always keep all your devices up to date, and by the way... What are you waiting for to update your Linux system?

Ok you can take the time to share this and give it a like, but after you must update your Linux system ;)