teleren/devto huggingface dataset:
How to create copies of a string in JavaScript?
Tags: solutions, repeatstringntimesja, stringclonejavascrip, stringrepeatjavascri
Published: 2021-03-04 05:31:43

---
title: How to create copies of a string in JavaScript?
published: true
date: 2021-02-20 12:56:38 UTC
tags: Solutions,repeatstringntimesja,stringclonejavascrip,stringrepeatjavascri
canonical_url: https://poopcode.com/how-to-create-copies-of-a-string-in-javascript/
---

To create copies of a string in [JavaScript](https://poopcode.com/category/javascript/), we can use String.prototype.repeat() method. It takes a number as an argument and repeats the [string](https://poopcode.com/string-contains-whitespace-javascript/) n times and returns it.

```
let str = "poopcode";

console.log(str.repeat(2)); //poopcodepoopcode

console.log(str.repeat(5)); //poopcodepoopcodepoopcodepoopcodepoopcode
```
ERROR: Error installing cocoapods: ERROR: Failed to build gem native extension
Published: 2021-02-20 12:56:36

Solution worked for Mac Big Sur OS

**NOTE** : replace user_name - with your laptop user name

1. Check the version of Ruby

     `ruby -v`

Also check the given path:
     `which ruby`


2. Use Homebrew to install the latest Ruby

     ` brew install ruby `

Binaries installed by gem will be placed into:

/usr/local/lib/ruby/gems/2.7.0/bin

3. Add this to your PATH.

If you need to have ruby first in your PATH run:

`echo 'export PATH="/usr/local/opt/ruby/bin:$PATH"' >> /Users/user_name/.bash_profile `



4. For compilers to find ruby you may need to set:

`export LDFLAGS="-L/usr/local/opt/ruby/lib"`
`export CPPFLAGS="-I/usr/local/opt/ruby/include" `

5. Follow the below instructions to set PATH. Now you will go to see the installed Ruby. 

`echo 'export PATH="/usr/local/opt/ruby/bin:$PATH"' >> /Users/user_name/.bash_profile `

`echo 'export LDFLAGS="-L/usr/local/opt/ruby/lib"' >> ~/.bash_profile `

`echo 'export CPPFLAGS="-I/usr/local/opt/ruby/include"' >> ~/.bash_profile `

 `source ~/.bash_profile `

6. Finally, Make sure your PATH is in place.

`ruby -v`

` which ruby `


 7. Make sure you install by specifying the save destination as follows.

` sudo gem install -n /usr/local/bin cocoapods `
Fix Collapsing in CSS3
Tags: css, webdev
Published: 2021-02-20 12:48:48

Hi! Today I will discuss different types of collapsing in CSS, and how to fix them.

#### What is the definition of collapsing?
Collapsed element is an element with a zero height.

### Types of collapses that we will discuss:

1- Floating Elements Collapse.
2- Margin Collapse.
3- Absolute Positioning Collapse.
4- Empty Div Collapse. 

### Floating Elements Collapse.

This is a common problem with floated elements.

If we have an element, that contains nothing but floated elements, then this parent element will collapse.

#### Fixing it

We will apply the famous “**clear-fix**” to fix this problem.

It’s a fix applied to the after pseudo-element of the parent element.

{% codepen https://codepen.io/abdelrahmandeghedy/pen/rNMoYOq %}

### Margin Collapse.

Margin collapse happens when you set margin-top for an element, and margin-bottom for the element above it, then the total margin between the two elements is the max-margin between both of them, not the sum of the two margins. 

#### Fixing it

To eliminate that effect, set one of the two elements' display to be inline-block.

{% codepen https://codepen.io/abdelrahmandeghedy/pen/bGBrLaZ %}

### Absolute Positioning Collapse.

This type of collapsing happens if the parent container that holds the absolute elements doesn't have an explicit height or width, it will collapse. 

#### Fixing it

The solution is to give the parent container an explicit height or width. 

> Note: When you gave it a height, don't use percentages, as the parent of this parent (body) is not specified explicitly.


{% codepen https://codepen.io/abdelrahmandeghedy/pen/wvoqymO %}

### Empty Div Collapse.

If we have an empty div, with no content, then it will collapse.

#### Fixing it

We could insert some content in the div, by writing the HTML special entity **&nbsp** that corresponds to space. 

Another solution is to set a **min-height**, or a **height** (with no percentages) for the div.

{% codepen https://codepen.io/abdelrahmandeghedy/pen/PobKQdX %}

That's it for today! I hope you learned from it. Good luck!
DOUBTS...
Published: 2021-02-20 12:41:57

Can someone explain me the solution to the below snippet

var x=3;

var obj1={
    x:2,
    baz:{
        x:1,
        bar: function(){
            return this.x
            
        }
    }
}

var go = obj1.baz.bar

alert(go())
alert(obj1.baz.bar())
Using before_destroy callback to do some association logic
Tags: rails, backend, callbacks, associations
Published: 2021-02-20 12:35:51

Have you ever had the task to do some external logic on the model association on destroying a record?

Luckily, we did. After destroying a course, all users registered to that course should be notified and we are notifying the users in a background job using Sidekiq.  

Well, we might all think (or at least that's what we did, you might have read the docs. thoroughly :D) that it is straightforward, use a `before_destory` callback, notify the users then destroy the course. 


<img width="100%" style="width:100%" src="https://media.giphy.com/media/aVtdz7iNVPI1W/giphy.gif">






Not so fast. What we noticed is that whenever we tried to find the registered users, we could not find neither the users nor the course.  



Turns out the `before_destroy` callback is run after the record is deleted (but still not committed to the DB). Since callbacks are run in order, with the `dependent: :destroy` the associated records are deleted before the record is deleted. Thus, all of that is done before the `before_destroy` callbacks are called. 



Our model looked something like this:
```
class Course < ApplicationRecord
  has_many :course_members, dependent: :destroy
  before_destroy :notify_members
end
```
where notify_members take the user ids as parameters.

Okay you might be thinking okay stranger we get it just get straight to the solution, so here it is. There is actually two easy solutions mentioned in the docs.


####Sol. 1
**Place the `before_destroy` callback before the `dependent: :destroy` association**
```
class Course < ApplicationRecord
  before_destroy :notify_members
  has_many :course_members, dependent: :destroy
end
```



####Sol. 2
**Use the `prepend: true` option**

```
class Course < ApplicationRecord
  has_many :course_members, dependent: :destroy
  before_destroy :notify_members, prepend: true
end
```
When the prepend option is set to true, our callback is going to be prepended to the callbacks chain rather than appended.


I like to use the second solution better. However, either way your `before_destory` callback now is going to find the associated records safe and sound. 



Lastly, You might keep in mind that you might face a problem  if an exception was raised and the deletion was actually rolled back since the `before_destroy` is called before committing to the DB.




Reference: [active_record_callbacks](https://guides.rubyonrails.org/active_record_callbacks.html)
This documentation is beautifully and clearly written and you will find all what you need regarding callbacks thoroughly explained.
Z-Index Transition on Image using CSS
Tags: csshoveranimation, cssanimation, cardanimation, zindextransition
Published: 2021-02-20 12:29:18

Hello Friends, today in this blog we will learn to create Z-Index Transition on Image using CSS. As you know, in my earlier blog I have shared <a href="https://www.codinglabweb.com/2020/12/profile-card-design-using-html-css.html">Animated Profile Card using HTML & CSS </a>which you have like very much considering that animated profile card, now I will going to create a z-index transition on cards.

Z-Index is the property of CSS which is used to taking forward specific elements on the webpages. It is the essential property of web designing to overlapping or bringing forward particular elements, cards, text, images, and so on.

As you can see on the given image of our program that we are going to build today. All the images are overlapping each other. The last image is only visible to us, and we can't see other's full images. I have provided a small image icon at the bottom side of every image denoting a small tooltip. Basically in this program, we can see all the images by hover on that every particular image.

You Might Like This:
<a href="https://www.codinglabweb.com/2020/12/animated-alert-box-using-html-css-only.html">Popup Modal Box</a>
<a href="https://www.codinglabweb.com/2020/12/share-button-animation-using-html-css.html">Animated Share Button</a>
<a href="https://www.codinglabweb.com/2020/12/3d-flip-card-on-hover-using-only-html.html">3D Flip Card On Hover</a>
<a href="https://www.codinglabweb.com/2020/12/animated-share-button-using-only-html-css.html">Share Button with Tooltip Animation</a>
Scraping the Hacker News with Python and Beautiful Soup
Published: 2021-02-20 12:26:17

Today we are going to see how we can scrape Hacker News posts using Python and BeautifulSoup in a simple and elegant manner.

The aim of this article is to get you started on a real-world problem solving while keeping it super simple so you get familiar and get practical results as fast as possible.

So the first thing we need is to make sure we have Python 3 installed. If not, you can just get Python 3 and get it installed before you proceed.

Then you can install beautiful soup with...
We will also need the libraries requests, lxml and soupsieve to fetch data, break it down to XML, and to use CSS selectors. Install them using...
Once installed open an editor and type in...
Now let's go to the Hacker News home page and inspect the data we can get.
Back to our code now... let's try and get this data by pretending we are a browser like this...
Save this as HN_bs.py.

If you run it...
You will see the whole HTML page

Now let's use CSS selectors to get to the data we want... To do that let's go back to Chrome and open the inspect tool. We now need to get to all the posts... We notice that the data is arranged in a table and each post uses 3 rows to show the data.
We have to just run through the rows to get data like this...
This prints all the content in each of the rows. We now need to be smart about the kind of content we want. The first row contains the title. But we have to make sure we dont ask for content from the other rows so we put in a check like the one below. The storylink class contains the title of the post so the code below makes sure the class exists in THIS row before asking for the text of it...
If you run it. This will print the titles...
Bingo!! we got the post titles...

Now with the same process, we get the other data like a number of comments, HN user name, link, etc like below.
Notice that for getting the comments we try and find the fourth link inside the block that contains the hnuser details like so

item.find_all('a')[3].get_text()

That when run, should print everything we need from each post like this.
We even added a separator to show where each post ends. You can now pass this data into an array or save it to CSV and do whatever you want.

If you want to use this in production and want to scale to thousands of links then you will find that you will get IP blocked easily. In this scenario using a rotating proxy service to rotate IPs is almost a must.

Otherwise, you tend to get IP blocked a lot by automatic location, usage, and bot detection algorithms.

Our rotating proxy server Proxies API provides a simple API that can solve all IP Blocking problems instantly.

With millions of high speed rotating proxies located all over the world,
With our automatic IP rotation
With our automatic User-Agent-String rotation (which simulates requests from different, valid web browsers and web browser versions)
With our automatic CAPTCHA solving technology,
Hundreds of our customers have successfully solved the headache of IP blocks with a simple API.

The whole thing can be accessed by a simple API like below in any programming language.
OLM to PST Converter Software to Convert OLM files into PST file format
Tags: olmtopstconverter, macoutlook, windowsoutlook
Published: 2021-02-20 12:11:23

I would like to recommend you to use  this OLM to PST Converter Tool that can migrate single or multiple OLM files into PST file format at once. It can migrate all email items from OLM file like inbox, calendars, Tasks and Notes into PST file format. It also save resultant OLM files into HTML, MBOX, EML, PDF, vCard, EMLX, MSG, and vCal file format. 

It can export OLM files to Office 365 and a Live Exchange server Safely. It show the preview of all OLM files before the conversion to make sure the successful migration. It can migrate any size of OLM files into PST file format without any file size restrictions.

It maintain the data integrity and keep intact original formatting after the conversion. This software not required any type of technical skill to use this software. Before using this Software checkout it free demo version first to analyze the features and functions of this software. 

Click here to read more info:- http://www.filesrecoverytool.com/olm-to-pst-converter.html
Creating components
Tags: vue, webdev, javascript, firebase
Published: 2021-02-19 12:10:30

---
title: Creating components
published: true
date: 2021-02-19 12:10:00 UTC
tags: vue, webdev, javascript, firebase
series: Vue Full Application Build
canonical_url: https://hiltonmeyer.com/articles/series/pantry/5-components.html
---

_Code for this can be found in the [Github Branch](https://github.com/bikingbadger/pantry/tree/4-creating-components)_

Things are going to start increasing in size and one of the cool things about Vue is using components. So the first thing I want to do is create a directory in `src` called `components/ingredient`, this will be where I add all my ingredient related components. This is just the way that I've decided to go but you could have something else or a different layout. Again I'm learning as I go along here and trying to share that with you as I pick up new things or better ways of doing things. If all goes according to plan I would come back and update these files not with the correct way but rather a link to the new way of doing it. I still want others to see the process which I find sometimes missing in these polished tutorials.

```
mkdir src/components/ingredient
touch src/components/ingredient/AddIngredient.vue

```

With this done I create a file called `AddIngredient.vue` and add what we previously did [setting up the ingredient](https://dev.to/iarehilton/setup-ingredients-m80) view cut that all out and paste it into the new file.

_AddIngredient.vue_

```
<template>
  <div class="ingredient">
    <div class="add-ingredient-frm">
      <div>
        <label for="name">Name:</label>
        <input type="text" name="name" id="name" />
      </div>
      <div>
        <label for="category">Category:</label>
        <select id="category" name="category">
          <option value="legumes">Legumes</option>
          <option value="vegetables">Vegetables</option>
          <option value="fruit">Fruit</option>
          <option value="dairy">Dairy</option>
        </select>
      </div>
      <div>
        <label for="uom">Unit of Measure:</label>
        <input type="text" name="uom" id="uom" />
      </div>
      <div><button>Add</button></div>
    </div>
    <ul>
      <li>Milk</li>
      <li>Whole wheat flour</li>
      <li>Olive Oil</li>
    </ul>
  </div>
</template>

```

In `Ingredients.vue` in the `views` directory we import the newly created component and add it to the view we're using. This will get us back to where we were in the begining but with the added benefit of having broken up the code a bit and starting to use components.

_Ingredients.vue_

```
<template>
  <add-ingredient></add-ingredient>
</template>

<script>
import AddIngredient from '@/components/ingredient/AddIngredient.vue';

export default {
  components: { AddIngredient },
};
</script>

<style></style>

```
Add return of last command to your shell prompt 
Tags: bash, shell, terminal, linux
Published: 2021-02-20 11:10:45

Whenever we execute a shell command, it returns an integer value. When this value is `0`, last command was a success. Any other number is the error code. We can see the return of last command by printing the value of `?` variable.

To test this:
- Enter command `ls`
- Check it's return by command `echo $?`
- Enter some random letters and press Enter
- Check return by `echo $?`

You should get an error in the second time when you enter some random command
```
chinmay@CC-T480:~/Desktop$ ls
file
chinmay@CC-T480:~/Desktop$ echo $?
0    <-- Success
chinmay@CC-T480:~/Desktop$ a
a: command not found
chinmay@CC-T480:~/Desktop$ echo $?
127  <-- Error code
```

We will use this `$?` value in our prompt to see if our last command has passed or failed.

We also need to know about environment variable `PROMPT_COMMAND`. Bash provides an environment variable called `PROMPT_COMMAND`. The contents of this variable are executed as a regular Bash command just before Bash displays a prompt.

Since our bash prompt should contain status of last command, it should be set inside `PROMPT_COMMAND`.

First we will write a simple shell function to update the prompt with return code.
```sh
exit_code() {
    # Save the exit status of last command. This
    # needs to be done first otherwise exit status of
    # other commands will be stored in this variable.
    EXIT="$?"

    # PS1 needs to be reset or else it will
    # be appended every time to previous one.
    PS1=""

    # This will be final prompt, whatever set earlier will be
    # overwritten by this.
    export PS1="$EXIT \w $ "
}
```
Then we can add this function to our `PROMPT_COMMAND`
```sh
# exit_code Should be first command in `PROMPT_COMMAND' to be executed or # else return status will always be 0/true as it will hold return status of
# previous command.

# First we check if prompt command is empty or not.
# If empty, just add `exit_code' to it. If non empty,
# make it `exit_code:$PROMPT_COMMAND'
[ -n "$PROMPT_COMMAND" ] && PROMPT_COMMAND="exit_code;$PROMPT_COMMAND" ||
    PROMPT_COMMAND="exit_code"
```
After adding the above 2 snippets in your `.bashrc`, you get something like this:
```
chinmay@CC-T480:~$ exit_code() {
>     EXIT="$?"
>     PS1=""
>     export PS1="$EXIT \w $ "
> }
chinmay@CC-T480:~$ PROMPT_COMMAND="exit_code"
0 ~ $ ls Desktop/
file
0 ~ $ ^C
130 ~ $ a
a: command not found
127 ~ $ echo $?
127
0 ~ $ echo $?    # return of last echo command
0
0 ~ $ 
```
Note that the first number in our prompt is the return status of last command. For `ls`, we see a `0` as it ran as expected. When I ran command `a`, bash threw an error saying `command not found` and it's error code is `127` which we can see in next line. For pressing `ctrl-c`, we can see error code as `130`.

Checkout [designing a minimal bash prompt](https://dev.to/chhajedji/minimal-and-super-useful-shell-prompt-1g8l).
JavaScript Interview Question #16: typeof NaN
Tags: beginners, codenewbie, javascript, interview
Published: 2021-02-20 10:44:32

![js-test-16](https://learn.coderslang.com/js-test-16.png)

What's the type of `Not a Number`?	

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

In JavaScript, `NaN` means `Not a Number`. This is a special value that appears whenever JS can’t make sense of the numerical expression.

`NaN` also often appears during typecast. For example, if you try to convert the string into a number, the result will be `NaN`.

It may seem counterintuitive, but `NaN` is just a special number. Thus its type is considered to be `number`.

You can tackle this problem from a different angle and try to answer the question:

> What else `typeof NaN` can be?

---

**ANSWER**: the `typeof NaN` is `number`, which will be logged to the console.

[Learn Full Stack JavaScript](https://js.coderslang.com)
Firestore Data Validation
Tags: firestore, typesafety, typescript
Published: 2021-02-20 10:27:03

For [prepsheets.com](http://prepsheets.com) I use Firebase and Typescript. At the start I sort-of took type-safety to the extreme. I use [runtypes](https://github.com/pelotom/runtypes) to validate all the data that comes into the app and have firestore security rules which enforce a schema on the database. This is somewhat annoying, but I think it's end-positive as I can be sure of what data ends up in the database. 

---

The first step is to ensure only valid field names are submitted (to stop users storing lots of arbitrary data)

```jsx
function incomingData() {
   return request.resource.data;
}

function onlyHasAttrs(attrs){
   return incomingData().keys().hasOnly(attrs);
}

match /users/{userId} {
	allow create: if onlyHasAttrs(['name', 'email', 'picture', 'age']);
}
```

This uses the [hasOnly](https://firebase.google.com/docs/reference/rules/rules.List#hasOnly) function on lists. It checks if all keys in incomingData are in `attrs`

---

Next I ensure that fields are off the correct type. This is easy for `strings` and `numbers`

```jsx
function hasValidSchema() {
	return (
		onlyHasAttrs(['name', 'email', 'picture', 'age']) &&
		incomingData().name is string &&
		incomingData().name.size() > 0 &&
		incomingData().age is number
	);
}

allow create: if hasValidSchema();
```

---

Unfortunately things are more complicated with `lists` and `maps`. While you can ensure that a field is off the type `list` or `map` you can't validate the members of those objects. Or at least you can't validate an arbitrary number of them. See: [https://stackoverflow.com/a/58257828/3949864](https://stackoverflow.com/a/58257828/3949864). Apparently the firebase team is looking into this so you can help get list type safety faster by [filing a feature request](https://support.google.com/firebase/contact/support).

For `map` attributes I only allow them to be set or updated to being empty. I use `Cloud Functions` to actually set the data, validating whatever is passed with runtypes.

```jsx
function hasValidMap() {
	return (
		incomingData().map is map &&
		incomingData().map.size() == 0 ||
		incomingData().map == existingData().map
	);
}
```

For `lists` I either use `Cloud Functions` to set the data or impose a maximum length. For example say we let users list their interests, but they can only list 5. Then in security rules we can use:

```jsx
function hasValidInterests(interests) {
	return (
		interests is list &&
		(interests.size() < 1 || interests[0] is string) &&
		(interests.size() < 2 || interests[1] is string) &&
		(interests.size() < 3 || interests[2] is string) &&
		(interests.size() < 4 || interests[3] is string) &&
		(interests.size() < 5 || interests[4] is string) &&
		(interests.size() < 6)
	);
}
```
Answers with Explanation Plz!!
Tags: javascript
Published: 2021-02-20 10:22:46

1. console.log(10 + "20")
2. console.log(9 - "5");
3. console.log("Java" + "Script");
4. console.log(" " + " ");
5. console.log(" " + 0);
6. console.log("Dear" - "Friend");
7. console.log(true + true);
8. console.log(true + false);
9. console.log(false + true);
10. console.log(false - true);
React (Opinion/Respond)?:
Tags: midi, html, react, javasctipt
Published: 2021-02-20 10:19:42

Do you think its possible to build a webpage Hidden/Transparent/Invisible/MIDI/GRID/App, that can.. (wait for it)..

1. Offline, (within an environment) Users agree to EULA and install the App via FREE WiFi Signal, Accessing a React Webpage.
2. App is "installed" yet, invisible (accessing a hidden URL)  .
3. The App Triggers MIDI Sounds as users poke/touch/swipe/access their Smart Devices.
4. My Question is...
5. Being an invisible, top, z-index layer. Can users still maintain access to their device as usual? Or my concern is that it won't be possible to interact as-usual with their smart device if an invisible layer somehow limits access to the other functions on their device screens.
6. My Intention is to develop an app that Always Triggers MIDI Sounds, (which are only [volume] controlled at the "head" localized-LAN Server).

Thank you,
Buddy Jackson
#GitXome!

PS: I always create the Art way before the Product.. 
  ..and oftentimes I forget what I've created!