teleren/devto huggingface dataset:
Iterator Pattern
Tags: designpatterns, java, pattern, behavioral
Published: 2020-10-10 04:16:59

Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/2dlytw8fqdk0wldyjgqe.gif)

#Participants
* Iterator: defines an interface for accessing and traversing elements.
* ConcreteIterator: implements the Iterator interface. Keeps track of the current position in the traversal of the aggregate.
* Aggregate: defines an interface for creating an Iterator object
* ConcreteAggregate: implements the Iterator creation interface to return an instance of the proper ConcreteIterator

#Code#
```java
public class Main {

	public static void main(String[] args) {
		String items[] = { "Item A", "Item B", "Item C", "Item D" };
		Aggregate aggregate = new ConcreteAggregate(items);
		for (Iterator iter = aggregate.getIterator(); iter.hasNext();) {
			String item = (String) iter.next();
			System.out.println(item);
		}
	}
}

public interface Aggregate {
	 Iterator getIterator();
}

public class ConcreteAggregate implements Aggregate {
	private String items[];

	public ConcreteAggregate(String[] items) {
		this.items = items;
	}

	@Override
	public Iterator getIterator() {
		return new ConcreteIterator(items);
	}
}

public interface Iterator {
	public boolean hasNext();
	public Object next();
}

public class ConcreteIterator implements Iterator {

	private String items[];
	private int index;

	public ConcreteIterator(String[] items) {
		this.items = items;
	}

	@Override
	public boolean hasNext() {
		if (index < items.length) {
			return true;
		}
		return false;
	}

	@Override
	public Object next() {
		if (this.hasNext()) {
			return items[index++];
		}
		return null;
	}
}
```

#Output#
```
Item A
Item B
Item C
Item D
```

{% github https://github.com/eidherjulian61/design-patterns no-readme %}
{% link https://dev.to/eidher/principales-patrones-de-diseno-13ao
 %}
List comprehension in Python
Tags: python, tips
Published: 2020-10-20 10:07:15

---
title: List comprehension in Python
published: true
date: 2020-10-10 02:30:00 UTC
tags: Python,Tips
canonical_url: https://dev.corteso.com/list-comprehension-in-python
---

## What are list comprehension ?

It’s a feature of the Python language allowing to do many things like :

- Create a list in a concise way

- Filter list items

- Editing list items

## Structure

The structure of a list comprehension is quite simple. You start by writing an **expression** , followed by a **for** clause, and end with one or more **if** clauses.

## Examples

For this example I will use the following list:

```python
characters = ['Harry', None, 'Ron', False, 'Hermione']
```

Here I will use a list comprehension for two things:

- Removing the "False" and "None" items from the list
- Adding the word "Hello" in front of each name

If I wrote this in another language, I would probably write something like this:

```python
sorted_names = []
for character in characters:
  if(character):
    sorted_names.append('Hello %s' % character) print(sorted_names)
```

Here is now a list comprehension that allows to reach exactly the same result:

```python
sorted_names = ['Hello %s' % character for character in characters if character]
print(sorted_names)
```

The resulting code is much more concise and easier to read. At least it is when you separate the different parts.

In the previous example, list comprehension starts with the expression to add the word "Hello" in front of each name:

```python
'Hello %s' % character
```

We will then indicate the elements on which we will work (as in the for loop in the longer example):

```python
for character in characters
```

We end with the part allowing to filter the elements of the list. In this case, we will only execute the first expression if character is different from "False" and "None":

```python
if character
```

Once these elements are assembled and put in square brackets, we get the list comprehension seen previously.

It should also be noted that a list comprehension does not modify the original list, which is why I assign it to a new variable.

## Conclusion

As this short example shows, list comprehension is a powerful element of the Python language.

But be careful not to use it for everything and nothing! Some methods such as **map** also allow to modify the content of a Python list and may, in some cases, be more suitable than list comprehension.

I hope you enjoyed this article! Feel free to share it on social networks !
Flutter AppBar Example
Published: 2020-10-10 03:07:43

As a part of our [flutter tutorial](https://easyflutter.com/flutter-tutorial/) series, we’re going to explore [AppBar example](https://easyflutter.com/flutter-appbar-example/). Usually AppBar can be seen in top header position to display title, navigation and few action buttons.

This article originally published in https://easyflutter.com/flutter-appbar-example/

{% youtube BGDDEaDcDx8 %}


### Flutter AppBar Example Source code

```dart
Scaffold(
  appBar: AppBar(
    leading: Icon(Icons.menu),
    backgroundColor: Colors.brown,
    title: Text("EasyFlutter"),
    centerTitle: true,
    actions: [
      IconButton(
        icon: Icon(Icons.search),
        onPressed: () {
          print("Search Pressed");
        },
      ),
      IconButton(
        icon: Icon(Icons.more_vert),
        onPressed: () {
          print("More Pressed");
        },
      ),
    ],
  ),
)
```

Download latest source code at: https://easyflutter.com/flutter-appbar-example/
Fixing lazyload images with React Server-Side Render
Tags: react, ssr, hydration, lazyload
Published: 2020-10-10 03:04:21

I've recently realized my server render pages has a problem. The offscreen lazyload image don't show up.

_In case you don't know, offscreen images won't load until it shows up onscreen. It helps to reduce unecessery loading to improve performance._

As usual, I impletemented image lazy loading by (1) get all img elements, (2) move photo URL to `data-src`, and remove `src`. Then (3) observe whenever each of them scrolled onscreen, move the photo URL back to `src` to load.

It works when React running on the client-side. But when render on the server-side, the images don't show up.

Turn out, it's a little different. As usual, the server will return a hydrated React page. Then the client will re-render the page again as a normal React page.

The problem was, the lazyload function executed twice as well. The first time, `src` is a link, and set to `empty` after assigning the link to `data-src`. Then the second time, `src` was empty, and that empty value is again, assigned to `data-src`. And when users viewing the page, it will start to load an empty value.

I fixed this problem by checking if `src` is not empty, before moving it to `data-src`.

In case you're looking for the code, here is a basic lazyImages.ts with some favors (add loading class, check for offscreen images)
{% gist https://gist.github.com/hieunc229/ddcd208bccde5fc8c4e05a84881c526b %}

You can use the `lazyImages` as following:

```js
lazyImages();

// offset before the image is scrolled into view
lazyImages({ rootMargin: "100px" });
```

Posted on [Fixing lazyload images with React Server-Side Render](https://hieunc.com/posts/6fNu3@O9xp-fixing-lazyload-images-with-react-server-side-render)
12 Ways of Applying a Function to Python Pandas DataFrame
Tags: python, datascience, machinelearning, dataengineering
Published: 2020-10-10 02:43:40

Applying a function to rows of a Pandas DataFrame is one of the most common operations during data wrangling. There are many ways of doing it.

I plotted the performance of various ways of applying a function to each row of a Pandas DataFrame, for up to a million rows.

![Performance of various alternative for applying a function to Pandas DataFrame](https://dev-to-uploads.s3.amazonaws.com/i/j21h793oe9vmah7qy81u.png)

I was surprised to see itertuples() beating apply(), and humble list comprehension beating them both.

So far, I was using apply() whenever I found vectorization difficult. Somehow I thought it was the 2nd best option.

I have been using "%timeit" often. In this exercise, I learned how to do line-level profiling in Python and also plotting the performance over input size.

[Continue reading » ](https://www.ml4devs.com/articles/pandas-dataframe-apply-function-iterate-over-rows/)
UnauthorizedError: invalid signature
Tags: node
Published: 2020-10-10 02:24:50

I'm having this error in the backend of my application, I think it's because of express-jwt exactly in my secret.
whenever I try to create a new category the error appears.
if anyone wants to help me I will leave the links to my repository down here.
backend: https://github.com/Amiltonxavier/ecommerce-backend.git
frontend:  https://github.com/Amiltonxavier/ecommerce-frontend.git
Going into the nature
Tags: health, productivity
Published: 2020-10-10 02:02:55

---
title: Going into the nature
published: true
description: An experiment to reduce stress and boost health, immunity + performance.
tags: #health #productivity 
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/reqspc7e6ry13bkqktwc.jpg
---

Hey folks!

Today I want to talk about an "experiment" I'm doing this weekend.

It's my own take on the idea of doing a "Digital Detox".

Now that traveling restrictions have been lifted for the most part and I haven't moved anywhere farther than my neighborhood's stores.

I'll be spending the next 2 days going into nature, in the countryside, completely disconnected from any electronic devices and any Wi-Fi networks.

I'll just take a backpack with some clothes, a couple of books, a notebook and a pen. Yeah, as analog as it gets.

I'm really a city kind of guy, I enjoy more spending time where there are things to do, people to interact with and have the possibility to be connected pretty much anywhere. 

But with anything, too much of a good thing starts to turn into a bad thing. So too much of technology, virtuality and everywhere connection starts taking a toll on the overall productivity, wellbeing and health that one has.

We can't let our lives be filled by too much of something whether that's perceived as 'good' or 'bad'. There needs to be some balance on all things going on in our lives.

![Thanos quote](https://i.imgflip.com/4hzv0u.jpg) 

Also, it is a good thing to listen to your body, be aware of what is trying to tell you and keep your mood in check. 

We all know about burnout 'till this point and the effects it has on our performance at work, the quality of the code we write and several other aspects of our lives.

My intention is doing a "back to the basics" kind of thing and then come back on Monday when I have to get back to work feeling completely refreshed, with batteries recharged and with my mojo back to take on the rest of the month in the best way.

So yeah that's pretty much it. I'll be doing something not new but very different from what I usually do and see what happens, how things turn out, maybe I will like it and start doing it more often who knows.

I'll probably also be reporting how it went when I come back in the form of a post on my experiences if it was worth it or not and reasons why you should try it as well. We'll see how it goes really I'm not bringing any _big_ expectations or anything.

That's it for this week's post, thanks again for reading this much shorter post than usual. I wanted to do something different for a while but again, I hope it was useful in some way and also hope to see you next week for another one.

---

<span>Photo by <a href="https://unsplash.com/@arslanbekov?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Denis Arslanbekov</a> on <a href="https://unsplash.com/s/photos/countryside?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></span>
Can Programming be Emotional?
Tags: opensource, javascript, discuss, beginners
Published: 2020-10-10 01:19:09

---
title: Can Programming be Emotional?
published: true
description: Omar Rizwan joins Henry to chat about the Dynamicland way of thinking: communal, involving the whole person, user agency. We discuss user control, the problem of lists, industrial open source, materiality and embodiment, knowing through doing, and being aware of your emotions when programming.
tags: opensource, javascript, discuss, beginners
//cover_image: https://direct_url_to_image.jpg
canonical_url: https://hopeinsource.com/emotional
---

Why do we experience the dread of using certain tools over others (debugger vs. console.log)? Have you thought about how you feel when programming?

> [35:31](https://hopeinsource.com/emotional/#t=35:31) *Omar*: Once I kind of started introspecting about like, what am I thinking and feeling when I'm programming and why am I not doing things? I noticed that there were all these weird emotional forces that are really determinative of what I'm doing at any given time.

{% twitter 1313245209917087745 %}

> [35:45](https://hopeinsource.com/emotional/#t=35:45) *Omar*: And I originally noticed the debugger thing, I tweeted about this, because I was TAing a class in college with freshmen and sophomores who were learning how to program in C and they hated using the debugger. Like they would do almost anything to avoid, to avoid having to pull up the debugger. And again, it's always tempting to tell them. we did usually tell them, like, why don't you open the debugger? But I think at the same time, there's something to learn from that. Like, why don't people want to use the debugger?

Do emotions matter when we are programming, or is that something we leave at home? Or is it something we should hone in on? 

{% spotify spotify:episode:0dwd9srgLR1UTG1XBu9JNb%}

[Omar](https://twitter.com/rsnous) joins me to talk about his time working on [Dynamicland](https://dynamicland.org/), or rather, more the way of thinking about programming that Dynamicland tries to embody.

(maybe you've heard of [Bret Victor](https://twitter.com/worrydream) from famous talks like [Inventing on Principle (55min)](https://vimeo.com/36579366) or [Learnable Programming](http://worrydream.com/LearnableProgramming/))

It's not just able making coding easier, but making computation a more dynamic medium in the sense of using the real world: space, community, our bodies.

In this 40min podcast we talk through a bunch of Omar's tweets: the tyranny of using a list for every UI, how design can at many terms remove a user's control, materiality of physical books, how tech is seen as discrete features vs. a coherent whole, epistemology and knowing things like people, end user programming, and the importance of understanding our emotions when coding.

- Full transcript at https://hopeinsource.com/emotional!
- [initial tweet](https://twitter.com/left_pad/status/1313207316649476098?s=20)
Learning Heap Sort in Javascript
Tags: beginners, computerscience, javascript, algorithms
Published: 2020-10-10 01:12:29

In this week's post I'll be going over how to do a heap sort using javascript. In a [past post](https://dev.to/123jackcole/learning-heaps-in-javascript-1ocf) I've discussed heaps as a data structure. Since this sort utilizes a heap I recommend checking out that first.

Now onto the heap sort. Heap sort works similarly to [selection sort](https://dev.to/123jackcole/sorting-algorithms-in-javascript-part-2-40o1) in that they both find the maximum element and place it at the end.

## Helper Methods

Due the the comparing we're going to be doing between elements it's a good idea to have a method that can easily swap the location of elements. We can easily do this using some fancy ES6 syntax.

![Swap](https://dev-to-uploads.s3.amazonaws.com/i/ga3s4kckuwwkltv82zt7.png)

We're also going to need a method that turns an array into a max heap. Remember that this means that each node will be  greater value than it's children.

![Heapify](https://dev-to-uploads.s3.amazonaws.com/i/agydp6rd3iuku8be0e5k.png)

## The Sort

The function works by taking the input array and turning it into a max heap. From here we swap the location of the root node and the last node, and then we reduce the size of the heap by one, effectively removing the largest value. We then repeat this process until there are no more values in the heap.

![Heap Sort](https://dev-to-uploads.s3.amazonaws.com/i/fp145d2fwjced9nwsdsp.png)

Heap sort has a runtime of O(nlogn). This means that a good situation to use a heap sort is when you're want a consistently timed sort (in games) but don't necessarily need the quickest solution every time. Heap sort will always have a O(nlogn) whereas a quick sort is often faster but can potentially be very slow. 

Thanks for reading! The code for this post can be found [here](https://github.com/123JackCole/Heaps).
Flutter wordpress app (Android & ios)

Tags: flutter, dart, wordpress, firebase
Published: 2020-10-10 00:24:53

https://codecanyon.net/item/flutter-wordpress-app-android-ios/28896018


Flutter for wordpress is an app that does convert your Wordpress website into a mobile true native app with customized contents within a fillip. What is “customized content”? Flutter for wordpress transfers exactly all contents with different formats that you created in Wordpress website into your mobile app without any coding skill and development time. To engage with customers in mobile, we need mobile app. Flutter for wordpress maximizes your customer’s experience and usability through UX flow in both Android and iOs. Features availables Compatible with any Wordpress site – the app is used the default Rest API from Wordpress to synchronize both sides from Website to Mobile app and vice versa Great UX design smooth home page and post navigation, varies built-int Flutter widget, quick blogs filter, searching keyword history… Flexible Design System – easy to config the homepage, category, Blog with a bunch of built-in components: Banner Slider, Banner Grouping, multi-columns Blog view… Powerful User Setting – the ability to enable the push notification, view wishlist, rate the app on app stores, Different themes, Smart Chat setting, switching languages Push notification – via Firebase and oneSignal Instance Synchronization – from mobile to the server and vice versa, the data will be updated smoothly without waiting for time. 60 frames per second (fps) app – working really well on both iOS and Android Support Smart Chat integrate with realtime Firebase, works with any Chat app like Messenger, WeChat, Whataspp… and also support the Intercom service. 3 type of Blog Detail screens – change to difference sexy blog detail news via config file. Multi-Languages – support to switch to any languages and easy to add your own Languages, also Right To Left (RTL) languages. Different themes and colors – Support a lot of themes with different colors which save locally in the app DeepLink – support for both ios and android, to help to reach to your app easier via another outside channel, such as route the user from website to open your app.

Demo Url : http://www.mediafire.com/file/6eio08vjp6bxa96/News_%25281%2529.apk/file
Configure Managed Identity for Azure Functions using PowerShell
Tags: azure
Published: 2020-10-10 00:23:55

This is going to be a sweet and short blog post on programmatically setting up a System-Assigned Managed Identity on an Azure Function App and assigning the appropriate permissions.

On an authenticated PowerShell session - I love to use Cloud Shell, either on my Windows Terminal or in the Azure Portal, type the following:

```
Update-AzFunctionApp -Name <YourFunctionAppName> -ResourceGroupName <YourResourceGroup> -IdentityType SystemAssigned
Connect-AzureAD
$managedIdentityId = (Get-AzureADServicePrincipal -SearchString '<yourFunctionAppName>').ObjectId
New-AzRoleAssignment -ObjectId $managedIdentityId -RoleDefinitionName "Contributor" -Scope "/subscriptions/<YourSubscriptionId"
```
What does this script do? Let's take it step by step
First we configure the Azure Function App to use a Managed Identity
Next, we retrieve the Managed Identity `ObjectID`. This is required by the next statement so that we can assign the appropriate RBAC role. The last line assigns the **Contributor** role to the Managed Identity with the Subscription being the scope. You can reduce scope to a resource group or specific resources instead if that's what you need.

> Reminder: System-Assigned Managed Identities are tied to the Resource that were created. As such, if that resource gets deleted, the Managed Identity will deleted with it

As promised, short and sweet
Watch tutorials and code in HTML, CSS, and JS from a SINGLE TAB!
Tags: css, html, javascript, showdev
Published: 2020-10-10 00:14:35

✨ DomeCode's Fusion has auto-complete now as well! ✨
Fusion saves you from the hassle of :
- opening a chrome tab for localhost
- a tab for tutorial
- code editor

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/41ltt47m4eaakquq027s.png)
https://domecode.com/fusion/ does all of this in a single tab!

Github: https://github.com/the-domecode/domecode-opensource/
Discord: https://discord.domecode.com/

If you want to work on DomeCode, join our Discord!
How to toggle attribute values using jQuery
Tags: jquery, toogle, attribute
Published: 2020-10-10 17:41:51

---
title: How to toggle attribute values using jQuery
published: true
date: 2020-10-10 00:00:00 UTC
tags: jquery, toogle, attribute
canonical_url: https://glpzzz.dev/2020/10/10/toggle-attribute-value-jquery.html
image: https://glpzzz.dev/assets/toggle-attribute-value-jquery.png
---

I just came across a very simple [question on StackOverflow](https://stackoverflow.com/questions/64290056/how-to-use-button-action-to-toggle-between-two-states-of-a-textarea-using-jquery). In the end is how to toggle the value of an attribute using jQuery.

## The long version

This is the explanatory version I created when the author of the question requested for an explanation of my original code. Most of the comments are obvious.

```
$('thebutton').click(function(){
   var currentRows = $('thetextarea').attr('rows'); //obtain the current number of rows in the textarea
   var newRows; //declare a variable to hold the new number of rows
   if(rows == 1){ //if just one...
       newRows = 5; // it should become 5
   }else{ 
       newRows = 1; //else, (not 1), become 1
   }   
   $('thetextarea').attr('rows', newRows); //assign the new value to the rows attribute of the textarea
});
```

## Short version version

My original answer was...

```
//short version, the one in the answer
$('thebutton').click(function(){
   $('thetextarea').attr('rows',  $('thetextarea').attr('rows')==1?5:1);
});
```

I've created a [gist](https://gist.github.com/glpzzz/762afe32e8c245216869e9b1bd0aaac0) for this two versions.

## The fancy version (new for me)

I still had the doubt if this could be done easier, and find the next way thanks to this [answer](https://stackoverflow.com/questions/18665031/how-to-toggle-attr-in-jquery/18665152#18665152):

```
$('thebutton').click(function(){
   $('thetextarea').attr('rows',  function(index, attr){
       return attr = 1 ? 5 : 1;
   });
});
```

Just learnt a new thing today. I can sleep easy.