teleren/devto huggingface dataset:
Two Approaches: Sorting an Array by Parity
Tags: beginners, interviewing, ruby, leetcode
Published: 2019-08-09 19:36:01

---
title: Two Approaches: Sorting an Array by Parity
published: true
description: Brute force versus an optimized approach
tags: beginners, interviewing, ruby, leetcode
---

In my interviewing adventures I have ran into a handful of questions that have provided great frameworks for solutions to reference in future problems. One such question is the [Sort Array By Parity](https://leetcode.com/problems/sort-array-by-parity/) problem.
## Problem
*Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A.
You may return any answer array that satisfies this condition.*

## Brute Force:

```
def sort_array_by_parity(a)
    i = 0
    j =  a.length - 1
    while i < j
        if a[i] % 2 > a[j] % 2
            temp = a[i]
            a[i] = a[j]
            a[j] = temp
        end 
        if a[i] % 2 == 0
            i += 1
        end
        if a[j] % 2 == 1
            j -= 1
        end
    end
  return a
end
```
In my first attempt at this problem I decided to try a two pointer approach and iterate towards the middle of the array. This solution passed the tests but had a runtime of 56ms placing it solidly slower than the majority of ruby submissions on LeetCode. So let's do better!

## Final Solution:
```
def sort_array_by_parity(a)
  # create an index to store the next even number you run into
  index = 0
  i = 0
  #iterate through
  while  i < a.length 
     # if you encounter an even number move it to a[index]
    if a[i] % 2 == 0
      temp = a[index]
      a[index] = a[i]
      index += 1
      a[i] = temp
    end
    i += 1
  end
  return a
end
```
This solution earned me a runtime of 40ms and beat 98.98% of all other ruby solution submissions. 

# My Takeaways
- Using an index variable can be useful for tracking where you want to place the next instance of something
- temporary variables can help you switch variables an array

Happy problem solving!
Reuseable component logic
Tags: react
Published: 2019-08-09 18:53:16

I am implementing a custom table that will have pagination, filtering, sorting, and other common features.  I do not want to use an existing solution, both because this is a good exercise to get familiar with React and because I want the table tailored to my needs.

The issue I'm running into is with the filtering.  What I want is to put the "does object pass filter" logic in the Filter; I've used this pattern successfully in other languages and it's very clean.

However, with React all of the logic has to go in the parent because the parent can't call methods on the child.  So I'm stuck. 

Here's what I *want* to do, roughly.

```
class FilterContainer extends Component {
  constructor(props) {
    super(props);

    this.toggle = this.toggle.bind(this);

    this.state = { isOpen: false };
  }

  toggle() {
    this.setState({ isOpen: !this.state.isOpen });
  }

  render() {
    return (
      <Fragment>
        <FaFilter id="filter-icon" />
        <Popover placement="right" isOpen={this.state.isOpen} target="filter-icon" toggle={this.toggle}>
          <PopoverHeader>Filter table</PopoverHeader>
          <PopoverBody>
            {this.props.children}
          </PopoverBody>
        </Popover>
      </Fragment>
    );
  }
};

class Filter extends Component {
  constructor(props) {
    super(props);

    this.setValue = this.setValue.bind(this);
  }

  setValue(event) {
    this.props.setValue(this.props.name, event.target.value);
  }

  // I want this as a method on the filter because I will have different types of
  // filters, and I don't want to duplicate this everywhere I use a filter
  passesFilter(obj){
    if (obj.hasownproperty(this.props.name)){
      if (obj[this.props.name].contains(this.props.value)){
        return true;
      }
    }
  }

  render() {
    return (
      <Fragment>
        <Label>
          {this.props.name}

          <Input
            id={this.props.name + "-value"}
            type="text"
            value={this.props.value}
            onChange={this.setValue} />
        </Label>
      </Fragment>
    );
  }
};
```

But now imagine instead of Filter, I had a StringFilter which could handle case sensitivity and regex, a BoolFilter which is just true/false, maybe a DateFilter, etc.  Each one of those has the concept of "passes filter", and duplicating them in the DataTable as well as anywhere else I want to use them sucks.

Hopefully this makes sense, if not I can provide more detail.
Help: NYC Beginner Coding Meetup
Tags: help, beginners, codenewbie
Published: 2019-08-09 18:42:49

Excuse me if this is the wrong place to post this, but I'm desperately searching for beginners (especially females or female-identifying, but open to anyone) who want to meet up in NYC (Brooklyn specifically) and discuss things like HTML/CSS/JavaScript, programming techniques and ways to solve problems, and more advanced topics like making a Gatsby website, using the mac terminal (basic commands as well as installing packages), Git and GitHub, basic website knowledge like APIs and just how the Internet works in general, and bootcamps/online courses such as Treehouse or Udemy.

I've thoroughly checked Meetup.com for events but none of them are really what I'm looking for. I'm also a member of Lesbians Who Tech and Women Who Code but both of those groups don't really have events very often, especially geared toward beginners.

I'm also really struggling as a self-taught "developer" so any advice for a beginner is welcome!
What have you learned this week?
Tags: discuss, motivation, beginners, weeklyretro
Published: 2019-08-09 18:36:27

---
title: What have you learned this week?
published: true
tags: discuss, motivation, beginners, weeklyretro
---

As the title says, what have you learned this week and would like to share with others? It could be a whole framework, some cool trick, best practice... whatever comes to your mind and is related to your profession.

For beginners, this could be a good place to get some quick tips and tricks on topics you're currently learning. This could also serve as a motivation to learn more and inspire.

I always try to work on a project or learn something new every week. And this week, one of the things I've learned the shorthand syntax for `<Fragment></Fragment>` in React is `<></>`.
Request Api Adapter
Tags: javascript
Published: 2019-08-09 18:31:03

When developing client applications, it is often necessary to send requests to the server.

```javascript
// ...
client({ url: "/users.json", method: "GET" }).then(...)

```

We can make our lives a little easier. A convenient abstraction is apiAdapter

```javascript
// apiAdapter.js
function getUsers() {
  return { url: "/users.json", method: "GET" };
}

const apiAdapter = createAdapter(client, {}, {
  getUsers,  
})
```

By defining a request in one place, you can now simply call the adapter method you want.

```javascript
import apiAdapter from './apiAdapter'

apiAdapter.getUsers().then(...)
```

It is also a useful option to specify basic settings for all requests, as well as handling errors and successful requests.

```javascript
const apiAdapter = createAdapter(
  client,
  { withCredentials: true },
  {
    getUsers,  
  },
  successHandler,
  errorHandler, 
)
```

[Github](https://github.com/atamurana/request-api-adapter)
[Live example](https://codesandbox.io/embed/new-ywzqb)
Automatic Vertical Scaling of the Java Heap
Tags: java, jvm
Published: 2019-08-09 17:57:27

---
title: Automatic Vertical Scaling of the Java Heap
published: true
description: 
tags: Java, JVM
cover_image: https://thepracticaldev.s3.amazonaws.com/i/0t78qiojtk7zdq87j47u.jpeg
---

For years java was synonyms of greedy applications, the kind that opens the refrigerator at night and eat all the available resources until the crash. The main reason for that behavior was the lack of an efficient way to give back the operational system the memory allocated in the java heap and not used anymore.

However with the new feature released on OpenJDK 12 for [Automatic Vertical Scaling of the java Heap](http://openjdk.java.net/jeps/346) in combination with [Shenandoah Garbage Collector algorithm](https://wiki.openjdk.java.net/display/shenandoah/Main)  the JVM now is able to dynamically scale the java heap and give back the committed memory to the SO when necessary. That´s an amazing feature that will allow you to save money when running your microservice application on a cloud environment that usually fees you by the used resource. 

Check this [VIDEO](https://www.youtube.com/watch?v=_NOOljpSM08) out (Slides [here](https://www.slideshare.net/jelastic/elastic-jvm-automatic-vertical-scaling-of-the-java-heap?ref=))


This post was originally released on my [Blog](https://educosta.dev/blog/automatic-vertical-scaling-of-the-java-heap/). If you have any doubts or questions feel free to drop a comment here or reach me out on Twitter [@educostadev](http://twitter.com/educostadev).
Beautiful Websites Designed with Free or Open Source Fonts
Tags: showdev, webdev, design
Published: 2019-08-09 17:50:28

Hi everyone,  

I started working on my first open source project: [Open Fonts](http://bit.ly/openfonts). It's a curated collection of websites that were designed with free or open source fonts. 

I started this project because I wanted to create a way to find inspiration for using free fonts. Each font listed is linked to a place where you can download it from, alongside with a list of websites that use the font.

Feel free to contribute.  Would love feedback/suggestions.

I hope this resource inspires the design of your next project.
I can't find my Reading list on dev.to
Tags: help
Published: 2019-08-09 17:10:17

---
title: I can't find my Reading list on dev.to
published: true
description: 
tags: help, 
---

It's been a while since this is happening, I can't find my reading list although it contains a number of articles

![reading list](https://thepracticaldev.s3.amazonaws.com/i/mn29ghyvsdqxkuki9zrs.PNG)

but whenever i visit the link this is what am getting, an empty reading list.

![Empty Reading list](https://thepracticaldev.s3.amazonaws.com/i/xdhc0un5mwgh00x0zj7a.PNG)

Can any body help!
Suggest some GitHub/GitLab react.js-redux projects 
Tags: react, redux, reactnative, webdev
Published: 2019-08-09 16:38:28

---
title: Suggest some GitHub/GitLab react.js-redux projects 
published: true
description: 
tags: react.js, redux, react-native, webdev
---

Hi, everyone I am looking to contribute or work on some of your projects that are available online GitHub, GitLab. I want to practice more on UI creation and implementing complex functionalities. 

It would be more awesome if I can see something with react-native because I have had very less experience with the same. Today I mostly learn about how to search on github and look up to topics and discover sections like this : https://github.com/topics/react

I have also been recommended following projects:
- https://github.com/bvaughn/react-window
- https://github.com/bvaughn/react-virtualized

but I'm not quite sure that I will be able to do something such huge and complicated projects so looking forward to some medium sized or intermediate level of Projects.
Health for developers
Tags: discuss
Published: 2019-08-09 16:00:29

Long sitting hours leads to so many health problems. i am seeing lot of hip and heart opening exercises listed to cure "office bend".
We spend most waking hours on front of screen, in a chair.

For IT professionals back problems, mental stress etc are very common. What's your take on this? what you do to avoid it?

I am thinking of publishing a list of exercises under 20 minutes, which can help. what should be on it?
I Surrender
Tags: career, jobsearch, hiring, interview
Published: 2019-08-09 15:52:52

---
title: I Surrender
published: true
description: a time to fight and a time to let go, for today.
tags: career, jobsearch, hiring, interview
---
I surrender to you impostor syndrome, maybe you are just correct. Maybe the reason I just can't seem to find a Software Engineer role is that I'm just not good enough. So what, that I've made stuff in multiple languages across multiple domains, gotten certificates in ML and DL, taught and mentored dozens of students through projects even in languages and frameworks I did not know, somehow I'm just not good enough for even the most entry level roles or apprenticeship programs. (No, I haven't only applied for those.) 

Or maybe I am good enough and the thing I can't seem to overcome is the bias against people who look different or have a neurological condition, or just an unconventional background and experience like I do. How do I fight against people knowingly or unknowingly doing the wrong thing?

And so, I give up. I free myself from the burdens and expectations that I have placed on myself to overcome all this and grant myself the freedom of just letting it happen.

For today.

Monday, I'll be back.


Disclaimer: this post is an ode to my feelings and being shared in the hope that it will be cathartic to others experiencing similar feelings. THIS IS NOT IN ANYWAY A REQUEST FOR ADVICE ABOUT THE JOB SEARCH PROCESS. IT CERTAINLY DOES NOT ELABORATE ON THE VARIOUS APPROACHES I'VE TAKEN.

Having said that, feel free to contact me if you want to work with me 😁
What was your worst new job experience?
Tags: career, discuss
Published: 2019-08-09 15:46:00

---
title: What was your worst new job experience?
published: true
description: Sometimes you start a new job and quickly realize it's not a good fit. What's your worst new job story?
tags: career, discuss
---

Sometimes you start a new job and quickly realize it's not a good fit. What's your worst new job story?
I'm a senior developer and I regularly google "html image tag"
Tags: discuss, beginners, culture
Published: 2019-08-09 15:38:31

---
title: I'm a senior developer and I regularly google "html image tag"
published: true
description: What's something you do that would surprise a junior developer?
tags: discussion, beginners, culture
---

Based on the Twitter meme from a few years back (kind of hard to search for but I'll add an example as soon as I find one), I'd like to hear the ways that you're not quite as smart/knowledgable as a junior dev might expect.

For me all of HTML is still a foreign language and I regularly google the most basic elements!
What was your win this week?
Tags: discuss, weeklyretro
Published: 2019-08-09 15:32:34

---
title: What was your win this week?
published: true
description: Got to all your meetings on time? Started a new project? Fixed a tricky bug?
tags: discuss, weeklyretro
cover_image: https://cl.ly/188e843c2985/download/Image%202019-02-15%20at%202.36.37%20PM.png
---

👋👋👋👋

Looking back on your week -- what was something you're proud of?

All wins count -- big or small 🎉

Examples of 'wins' include:

- Getting a promotion!
- Starting a new project
- Fixing a tricky bug
- Cleaning your house...or whatever else that may spark joy 😄

![funny-doggo](https://media.giphy.com/media/4Zo41lhzKt6iZ8xff9/giphy.gif)

Happy Friday!
Compound scales in D3.js
Tags: d3, javascript, dataviz, webdev
Published: 2019-08-09 15:14:14

---
title: Compound scales in D3.js
published: true
description: "Leverage the power of D3 scales for maximum flexibility in your datavisualisation"
tags: #d3 #javascript #dataviz #webdev
canonical_url: "https://nobitagit.github.io/blog/d3-compound-scales/"
cover_image: "https://images.unsplash.com/photo-1529651795107-e5a141e34843?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max&ixid=eyJhcHBfaWQiOjF9"
---

Scales are an extremely flexible feature of D3.js.
Even though in many cases our need is just to have a function that maps one value in the `domain` to one value in the `range`, sometimes it can be handy to have a mapping from one to many values.

Suppose for example that we need to map one input to a set of values such as color and radius to build a simple scatterplot where the dots have radius and color depending on the input value from the dataset.

In these case being able to have a compound scale is what we need, and thankfully D3 provides this feature out of the box. Just pass two (or more) objects to the range function and d3 will do the rest.

Here’s a simple example:

```js
const myScale = scaleLinear()
  .domain([0, 100])
  .range([
    {color: '#4c0080', radius:'15px'},
    {color: '#43a1ad', radius:'150px'}
  ]);
```

This code will return a function that will convert our values (in this case from 0 to 100) to an object with all the values appropriately interpolated.

For example:

```js
myScale(41); // => {color: 'rgb(72, 66, 146)', radius: '70.35px'}
```

A simple yet super-handy feature, especially considering that we don’t need to specify the interpolator because the library will figure it out for us. On top of that we are not tied to single level objects, but deep objects will work just the same.


## Credits

Image is by [Markus Spiske](https://unsplash.com/@markusspiske).

_Originally published on [my blog](https://nobitagit.github.io/blog/d3-compound-scales/)_.
How to Open BIG JSON files
Tags: json, productivity, webdev
Published: 2019-08-09 15:00:37

##Why

JSON is the most used format to store data, and until now, there were only text editors to handle it, and they are not the real proper solution as they will quickly lose effect and speed as the file size grows.

Whenever I was working with a new JSON-Based format, a DB dump or download an export, I faced this issue again. I couldn't open them properly, or if I could, I couldn't search in it or export a sub node. So one day, I chose to make my own.

##How

The main trick is to build a tool that views the JSON as JSON, not a text. I mean look how object and array form the result.
Then we need a new fast JSON parser that works in SAX. Luckily I know the [best one](http://blog.synopse.info/post/2011/06/02/Fast-JSON-parsing) written in FreePascal.
I couldn't store the tree and index much as it gets a lot of memory for a big file (eg, 1GB) so I review each node when I need it. All the same, done for export and search too, and that was another challenge to beat!

##Result

It beats all of the other solutions in performance, and it will give you a complete set of tools to work too. Tree highlighted view, Instant search including RegEx support, auto-refresh on file change and many export options including XML is just a part of its features.

Lets compare it:
- 10X faster than VSCode in launch
- 9X less RAM usage than Sublime
- 21X faster than NPP++ in search

##More

So this the FASTEST JSON viewer I ever saw. Do you know something faster? Let me know.
Take a look at it and let me know if you want to know more.
It is Free and available for download for Mac and Windows right now, and Linux version is on the way.
https://viewer.dadroit.com
Abusing Ruby Hashes for fun
Tags: ruby
Published: 2019-08-09 15:00:11

Every Ruby developer loves their hashes, they are available in the core, [O(1)](https://en.wikipedia.org/wiki/Big_O_notation#Orders_of_common_functions) (which means _fast_) for access, and they include the awesomest module in the world: [Enumerable](https://ruby-doc.org/core-2.6.3/Enumerable.html).

The fact, however that we are used to utilise the as mere dictionaries, or handy data aggregations whenever we can't be bothered to create a custom class.

That means that we usually only put `"strings"` or `:symbols` as keys. but hash keys are not limited to that, you can use anything that responds to `.hash` method, and that in ruby is _almost everything_.

So thinking about this I came around to try to test the limits of this idea:

Basic usage of hash, with booleans as keys:
```ruby
>> h = {true => '1 is odd', false => '1 is even'}
=> {true => "1 is odd", false => "1 is even"}
>> h[true]
=> "1 is odd"
```

Let's calculate the keys instead of using literal values
```ruby
>> h = {1.odd? => '1 is odd', 1.even? => '1 is even' }
=> {true=>"1 is odd", false=>"1 is even"}
>> h[true]
=> "1 is odd"
```

Let's change `1.odd?` for `p.odd?` so that it can be defined dynamically:
```ruby
>> p = 1; h = { p.odd? => "#{p} is odd", p.even? => "#{p} is even" }
=> {true=>"1 is odd", false=>"1 is even"}
>> h[true]
=> "1 is odd"

>> p = 0; h = { p.odd? => "#{p} is odd", p.even? => "#{p} is even" }
=> {false=>"0 is odd", true=>"0 is even"}
>> h[true]
=> "0 is even"
```

But that only works defining `p` before `h`, so let's go one step further:
```ruby
>> f = -> (p) { { p.odd? => 'odd', p.even? => 'even' }[true] }
=> #<Proc:0x00000002052bf0@(irb):49 (lambda)>
>> f[1]
=> "odd"
>> f[0]
=> "even"

```
And now, what if the procs from the keys could be more complex predicates, like *nested procs*:
```ruby
>> f = -> (p) { { ->(a) { a.odd? }[p] => 'odd', ->(a) { a.even? }[p] => 'even' }[true] }
=> #<Proc:0x0000563ce10524d0@(irb):10 (lambda)>
>> f[1]
=> "odd"
>> f[2]
=> "even"
```

Are you dizzy about the braces? Let's put this some othe way:
```ruby
>> f = proc do |p|
  Hash.new.merge(
    proc { |a| a.odd?  }.call(p) => 'odd',
    proc { |b| b.even? }.call(p) => 'even'
  ).fetch(true)
end
=> #<Proc:0x00000001fac070@(irb):52 (lambda)>
>> f[1]
=> "odd"
>> f[2]
=> "even"
```

You may as well tell me that this is a very convoluted way to tell the oddness of a number, but odd and even are here only to not distract from the explanation, the fact is that you can replace `proc { |a| a.odd?  }` for anything that accepts `.call` with the appropriate parameters and have a very lean classifier for any disjoint discreet set.

This is not necessarily the best way to do this, you might rather use a case/when statement. But at least I hope you can leave today with a broader idea of ruby hashes and what can go on their keys.

P.S: salutations to [@tholford0](https://twitter.com/tholford0) who _suffered_ this with no explanations as a whiteboard brain-teaser. (not an interview)
This time I did it in one line - a CodeWars challenge explanation
Tags: beginners, python
Published: 2019-08-09 14:35:36

I've developed a habit of writing [posts](https://dev.to/erikkristoferanderson/how-did-they-do-that-in-one-line-part-2-isograms-52p6) about one-line solutions to Kata (challenges) on CodeWars.  
In the past they've all been about one-line solutions written by other code warriors. But this time, I came up with the one-liner. I wasn't the first, but I did come up with it myself.  
The idea of this [kata](https://www.codewars.com/kata/exes-and-ohs/python) was to determine if a string had an equal number of "x"s and "o"s.  
Here's my solution:  
```
def xo(s):
    return s.lower().count('x') == s.lower().count('o')
```
Note: by one line I mean one line of function body.

I started with a return statement because the expression following it will return a boolean value: `True` if the "x"s and "o"s are the same in number, and otherwise `False`.

Now it gets a little dense, so I'll pick it apart. On each side of the equality test, we start with `s.lower()`. The result of this expression will be a lower case string. Let's call it `s.low`.  
Now we can see that `s.lower().count('x')` is equivilant to s_low.count('x'), which would return the number of the character 'x' in the string `s`.  
`s.lower().count('o')` will do the same thing.  
Now, on either side of the `==`, we have an expression for the number of one of those characters in the string `s`. If those numbers are equal, the function returns `True`. Else, the function returns `False`.


Note: a more readable solution would be:
```
def xo(s):
    s = s.lower()
    return s.count('x') == s.count('o')
```
This was actually my first idea, and it's the most popular solution for this kata on CodeWars. Since Python is all about readability, I'd have to say this is the better solution, but I've developed a fancy for one-line solutions.

I suspect I'll be back with another of these in the near future. Until then, enjoy and be well.

~Erik