teleren/devto huggingface dataset:
CSS Selectors - Summary
Tags: css, web, html
Published: 2020-04-22 15:27:45

---
title: CSS Selectors - Summary 
published: true
description: Types of css selectors with examples 
tags: css, web, html 
---

#### 1. Tag / Element selector

* Use the built-in html element name, e.g. div, body, span, p, ul etc.

```css
body
{
 // style applies entire body(including child tags)...
}
```

<hr/>


#### 2. Descendant selector 

```html

<p>
  <a>direct descendant</a>

  <span><a>Indirect descendant</a></span>
</p>

<style>
p a
{
  // Apply styles to all 'a'(anchor) elements withing the paragraph p
}
</style>
```

<hr/>


#### 3. Child selector 

```html
<p>
  <a>direct descendant</a>

  <span><a>Indirect descendant</a></span>
</p>

<style>
p > a
{
  // Apply styles to direct descendant only!
}
</style>
```

<hr/>


#### 4. Attribute selector 

* Select an element with a specified attribute

```css

p[id]
{
  // Apply styles to p element with id attribute set to anything
}


p[id='fist']
{
  // Apply styles to p element with id attribute set to 'first'
}
```


* [More exmples](https://www.w3schools.com/css/css_attribute_selectors.asp)

<hr/>


#### 5. Select by Id

* Probably the most common selector ??

```html
<body>
<div id="container"></div>
<div id="not_a_container"></div>
</body>

<style>

 #container
  {
   // style applies to div with id attribute set to 'container'
  }
</style>

```

<hr/>


#### 6. Select by Class 
* Second most common? No ? Ok.

```html
<body>
<div class="container"></div>
<div class="not_a_container"></div>
</body>

<style>

 .container
  {
   // style applies to div with class attribute set to 'container'
  }
</style>

```

<hr/>


#### 7. Pseudo selectors 

* Typically used to apply styles based on user events e.g. On mouse hover

```css

a:hover
{
  font-weight: bold;
}

// set the font weight of all links to bold on mouse hover

```
* [More examples](https://www.w3schools.com/css/css_pseudo_classes.asp)




<hr/>

* And finally......


#### 8. Nth Child Selector

* This is best explained using an example

```html

<div>
<p>
Fist
</p>

<p>
Second
</p>

<p>
Third
</p>


<p>
Fourth
</p>
</div>


<style>
p:nth-child(2n)
{
 color: red;
}

// This will affect each p element inside the parent div who's position is a //multiple of 2
</style>

```
Spring Boot : Unit Test
Tags: java, springboot
Published: 2020-04-22 15:27:30

Example of how to write unit test in Spring Boot.

```java
// UserController.java
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/users/{id}")
    public User findUser(@PathVariable Long id) {
        return userService.findById(id);
    }
}

// UserService.java
@Service
public class UserService {

    @Autowired
    private UserRepo userRepo;

    public User findById(Long id) {
        return userRepo.findById(id);
    }
}


// UserRepo.java
@Service
public class UserRepo {

    public User findById(Long id) {
        return User.builder()
                .id(id)
                .name("Mac")
                .build();
    }
}

// User.java
@Data
@Builder
public class User {

    private Long id;
    private String name;

}
```

* Test Service class

```java
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserServiceTest {

    @InjectMocks
    private UserService userService;

    @Mock
    private UserRepo userRepo;

    @Test
    public void testFindById() {
        Mockito.when(userRepo.findById(Mockito.anyLong())).thenReturn(User.builder()
                .id(1L)
                .name("Mac")
                .build());

        User user = userService.findById(1L);

        Assert.assertEquals(1L, user.getId().longValue());
        Assert.assertEquals("Mac", user.getName());
        Mockito.verify(userRepo, Mockito.times(1)).findById(Mockito.any());
    }
}
```

* Test Controller class

```java
@RunWith(SpringRunner.class)
@WebMvcTest(UserController.class)
public class UserControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private UserService userService;

    @Autowired
    private ObjectMapper objectMapper;

    @Test
    public void testFindUser() throws Exception {

        User user = User.builder()
                .id(1L)
                .name("Mac")
                .build();
        Mockito.when(userService.findById(Mockito.any())).thenReturn(user);

        mockMvc.perform(MockMvcRequestBuilders.get("/users/1"))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.content()
                        .json(objectMapper.writeValueAsString(user)));
    }
}
```

*Note*

* `@RunWith(SpringRunner.class)` is require if you use JUnit 4.
* By default, `@SpringBootTest` will not start server but you can configure it with `webEnvironment` attribute.

Reference : https://stackoverflow.com/questions/44200720/difference-between-mock-mockbean-and-mockito-mock
Twillio Hackathon - Stay at Home with CovidFighter
Tags: twiliohackathon, android
Published: 2020-04-22 15:24:38

## What I built
For twillio hackathon, we try to build a simple android app that show  Traditional Herb Drink Recipe from the ingredients until step to make it. Also we provide a physical distancing detector based on user location and Covid-19 realtime data 
## Demo Link
We try to complete our app so be patient and stay tune for any update from this post :)
## Link to Code
You need Android Studio to open it, and you can find our repo in [this link](https://github.com/rogcomfox/CovidFighter)

## How I built it 
I had build an app using kotlin and my partner had design many android app so we decide to collaborate to build this app. And also because covid-19 we have an idea about an app that make people aware from this pandemic and also provide a lot of information to improve immune system.


## Additional Resources/Info
This is our app preview
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/pxfd79iftuc9x28gtkks.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/c5esyt68e5x2l3mwpdd5.png)
Mudei de área depois de tanto planejar
Tags: javascript, css, html
Published: 2020-04-22 14:55:56

  Eu estava quase dez anos trabalhando com logística, minha graduação estava parada porque trabalhava muito longe da faculdade e meus planos de fazer um mestrado na área estavam meio que ficando de lado, estava num ritmo de trabalho muito intenso, não sei se era porque estava trabalhando numa startup onde tudo acontece muito rápido ou porque estava trabalhando com logística numa startup onde a velocidade se multiplica por dois, porém não estava feliz. Estava cansada de fazer um trabalho muito braçal e sem análise nenhuma, nesse período eu conheci a área de análise de dados e me interessei por conta das previsões que a mesma poderia fazer no meu trabalho e a otimização de todo o esforço somente pelo fato de poder saber das coisas antes, nada de mágica somente estatística e dados mesmo.
  Então decidi estudar mais essa área e fiquei encantada com tudo o que poderia ser feito com Power BI e Python, foi justamente conhecendo Python que conheci programação e vi que não um bicho de sete cabeças e que era possível aprender. Desde criança sempre gostei muito de tecnologia, no ensino médio até cogitei em cursar graduação na área, porém um colega de classe me disse que eu iria ficar o dia inteiro digitando linhas de códigos e isso meio que me desanimou e então a vida me levou para outro caminho que foi o da logística mesmo. Depois de tanto ler e estudar sobre a área de programação, enfim tive coragem de finalmente migrar mesmo de área, nessa época participei de um processo seletivo de bolsa num curso de programação patrocinado por um banco e me frustei muito, o material de nivelamento desse curso na minha opinião foi muito ruim, foi a inserção em Javascript da pior forma possível, mas mesmo assim consegui finalizar tudo e não consegui a bolsa de 100%, mas consegui a de 50%. Mas nessa mesma época eu tinha prestado para o Bootcamp da Reprograma e quando eu estava numa semana de puro stress com o trabalho e com a escola que eu tinha ganhado a bolsa parcial recebi o e-mail da Reprograma informando que tinha passado no curso integral de desenvolvimento front end, assim que li sentei e chorei literalmente. 
  E então larguei tudo, larguei o trabalho que eu estava quase 3 anos e ganhando bem e larguei a matricula no curso de full stack que eu tinha ganhado bolsa parcial para cair de vez no mundo da tecnologia e cursar a Reprograma, pretendo fazer mais post sobre a Reprograma e a minha jornada, mas finalizo esse post aqui com a minha trajetória nada planejada de como cheguei até aqui.

*Site Reprograma (https://reprograma.com.br/)
Any conservation foundations or initiatives that you'd recommend others look into?
Tags: watercooler, opensource, discuss, earthday
Published: 2020-04-22 15:14:03

---
title: Any conservation foundations or initiatives that you'd recommend others look into?  
published: true
description: Do you know of any conservation foundations or efforts that you'd recommend others look into? 
tags: #watercooler, #opensource, #discuss, #earthday
---
Today, we're celebrating Earth Day on DEV! 🌍🌏🌎

{% link https://dev.to/devteam/today-is-earth-day-devs-can-have-an-impact-f81 %}

As such, we thought it'd be cool to start a thread for folks to link to different conservation foundations and efforts so that others can learn more and potentially donate to these awesome initiatives!

![earth dance](https://media.giphy.com/media/joJT2zeWCWhLa/giphy.gif)

So, do you know of any conservation foundations or efforts that you'd recommend others look into? Please drop a link if so!
Javascript project Ideas
Tags: codenewbie, javascript, react, angular
Published: 2020-04-22 15:12:20

If you are a javascript developer or a beginner in javascript and have some extra-time during this quarantine/lockdown due to the COVID-19 pandemic .

You can try these simple projects to improve/brush-up your js skills.

Also, if you have great javascript project ideas, then mention them in the comment section below. It might help someone!

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/xaor45psvvnbdmb3xdqj.png)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/yg0wft2aio0gstp5xnhy.png)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/vgq7lsrp45q08hfh5z8x.png)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/q58okjlsy12c2as4f31w.png)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/z3vsd34ik92a1za8nzvv.png)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/tc3vpwjz7n1ae0iev9pa.png)
Javascript Notes, Part-02 - Callbacks and Higher-order functions
Tags: javascript, webdev, tutorial, beginners
Published: 2020-04-22 15:07:28

Remember one word when you write code, "DRY" *(Don't Repeat Yourself)*.

## Higher-order functions and callbacks.

Most of the code can be optimized, shortened, and modularized while writing functions. If you can modularly write code that doesn't repeat the same functionality then you are following the DRY principle.

## Some DRY principles

**Generalization:** First try to generalize your functions. If two functions do the same things then probably they can be combined to one.
 Example:
```javascript
function nineSquared() {
 return 9*9;
}

function tenSquared() {
 return 10*10;
}

//above code is not DRY

 function numSquared(num){
  return num*num
}

//generalized function

```

**Functions are first-class objects**
  * They can be assigned to variables.
  * They can be passed as arguments.
  * Can be returned from other functions.

**Higher-order functions:** A function that takes in a function as an argument or returns out a function.
**Callback functions:** Functions that are passed in as parameters to higher-order functions are called as callback functions.

We can use a callback function to DRY our code. Look at the below example where multiplyBy2 function acts as a callback function. Note that you can pass in 
 different functions as a callback function.

```javascript
function copyArrayAndAdd3(array) {
 const output = [];
 for (let i = 0; i < array.length; i++) {
 output.push(array[i] + 3);
 }
 return output;
 }
const myArray = [1,2,3];
const result = copyArrayAndAdd3(myArray);

//we are breaking the DRY principle in above

function copyArrayAndManipulate(array, instructions) {
 const output = [];
 for (let i = 0; i < array.length; i++) {
 output.push(instructions(array[i]));
 }
 return output;
}
function multiplyBy2(input) { return input * 2; }
const result = copyArrayAndManipulate([1, 2, 3], multiplyBy2);

//Here multipleBy2 is passed as callback function to higher-order function copyArrayAndManipulate.
//This callback function can be later invoked inside the parent function.
// multipleBy2 can be replaced with other functions, hence our code is DRY!
```

**Some Notes:** 
* Async JS: callbacks are the core aspect of async JS

* Parameters are passed in as a link back to where it was saved in global, We are not copying but sending the reference of the variable into a function.
* Blocks like for loop get their own protected namespace but not an entire execution context.
* Methods, They can be passed as inputs, as arguments into other functions, they reference back to where they were born, more on this later.
About Ruby Hash#default and Hash#default=
Tags: ruby, hash, documentation
Published: 2020-04-22 14:56:40

---
title: About Ruby Hash#default and Hash#default=
published: true
description: 
tags: ruby, hash, documentation
---

Get more information and more examples at my AboutRuby project:
* [AboutRuby project](https://github.com/BurdetteLamar/AboutRuby/blob/master/core/Hash/api/markdown.md#default)

Here's the write-up over at the Ruby project:
* [Ruby project](https://ruby-doc.org/core-2.7.0/Hash.html#method-i-default)

My main page is [here](https://github.com/BurdetteLamar/AboutRuby#about-ruby).

TL;DR

I've been working on enhancements to the documentation for the Ruby project.  Getting these enhancements posted to the Ruby project has been very slow.  They're not actually meeting resistance;  I know because my many PRs for enhancing class ENV were accepted (though not rapidly).  It's just that everyone is busy.

Anyhow, I'm stashing all this stuff on in my own project, called AboutRuby.  The piecemeal migration from there to the Ruby project is not going to be completed in my lifetime (I'm 77 years old).

So:  I'm going to blow my own horn here on DEV, to encourage you to use the enhanced documentation.
Today I learnt | 22 April 2020
Tags: windows, batchfiles, cmd
Published: 2020-04-22 14:42:28

---
title: Today I learnt | 22 April 2020
published: true
description: Don't mind me, this is just a personal notebook...
tags: windows, batch files, cmd, 
---


#### 1. Clear screen in windows cmd

```
> cls
```
* Similar to clear in unix 

<hr/>

#### 2. Modifying console colors

* Syntax: _color (background-color)(foreground-color)_
* Example:

```
> color 08

# Sets background to black and foreground(text color) to green
```

* More color codes
  - Black = 0
  - White = 7
  - Green = 8 etc.

<hr/>

#### 3. Creating aliases in windows cmd

* Example:
 
```
 > doskey ls = dir
```

* Now running ls in your cmd shell will list the files and directories inside the current folder.
* Note: This alias will be 'lost' when you close the current shell
Angular: Include module for specific environment
Tags: angular
Published: 2020-04-22 14:39:55

In Angular pre 9 we could do the following to include an optional module only for non prod builds/serves (e.g. a mock http interceptor):

```ts
const mockModule = environment.useMockBackend ? [MockModule] : [];

@NgModule({
  imports: [
    CommonModule,
    // ...
    ...mockModule 
  ],
  // ...
})
export class AppModule {
}
```
With the above setup the CLI would make sure no code of the MockModule would end up in builds for environments where `usweMockBackend = false`. This is important to keep the bundle size small.

With Ivy (Angular 9+) this doesn’t work any more and the optional module will be part of all builds (even though it might not be used at runtime). 

To actually exclude all code of the optional module from builds for specific envionments/configurations, we need to make sure not to import this module directly, but only reference it in the `environment*.ts`. This works, as the CLI makes sure only the correct file is included in the build:

```ts
@NgModule({
  imports: [
    CommonModule,
    // ...
    ...environment.optionalModules
  ],
  // ...
})
export class AppModule {
}
```
With e.g. `environment.ts`:
```ts
export const environment: Environment = {
  optionalModules: [MockModule],
};
```
and `environment.prod.ts`:
```ts
export const environment: Environment = {
  optionalModules: [],
};
```
At hindsight, this seems obvious, but as it did cost me some hours I thought it worth sharing :-)

## Bonus
Note, that with the above setup, the optional module cannot/should not reference the configuration in `environment.ts` as this would induce a circular dependency.
This can be resolved by creating a module factory that takes the needed configuration as parameter, such as:
```ts
  public static forRoot(config: OptionalModuleConfig): ModuleWithProviders<MockModule> {
    return {
      ngModule: MockModule,
      providers: [{provide: OPTIONAL_MODULE_CONFIG, useValue: config}]
    };
  }
```
PUBG Mobile UC Hilesi
Tags: css
Published: 2020-04-22 14:26:48

PUBG Mobile UC Hilesi 2020 arayan kişiler için açmış olduğumuz yepyeni bir web sitesi var. HTML+CSS+JAVASCRIPT ile kodladık. Hemen aşağıdan siz de pubg mobile hile deneyebilirsiniz.

https://hilesi.xyz
Styling your active classes in Nuxt.js
Tags: nuxt, vue
Published: 2020-04-22 14:16:20

---
canonical_url: 'https://debbie.codes/blog/nuxt-active-styles'
---
Nuxt.js, which uses `vue-router`, can easily tell what route you are on and therefore can add a class to that link when the user is on that page. By default this class is called `nuxt-link-active`.

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

In order to style your active links the only thing you have to do to is add the `nuxt-link-active` class to your styles and then you can style it as you wish.
 
```css
.nuxt-link-active{
   color:red;
}
```

Sometimes this will also add styles to other links such as the parent routes or the home page. In order to fix this we use the exact active class. By default this class is called `nuxt-link-exact-active`.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/tlw2t2dhrjmz2iyw7du3.png)

The only thing you have to do to is add the `nuxt-link-exact-active` class to your styles and then you can style it as you wish. 

```css
.nuxt-link-exact-active{
   color:green;
}
```

You can add this css to your navigation component or to a specific page or layout or in your global css file. See the [nuxt docs] (https://nuxtjs.org/api/configuration-css) for more information on adding global css files.

Should you want to you can also configure the classname to be something different. Although this is not necessary for it to work you might want to configure the classname to be a class that is already in your third party styles or configured in tailwind for example.

You can change the active class in your `nuxt.config.js` file using the `router` property and setting a value to `linkActiveClass`.

```javascript
export default {
  router: {
    linkActiveClass: 'my-custom-exact-active-link'
  }
}
```
You can change the exact active class in your `nuxt.config.js` file using the `router` property and setting a value to `linkExactActiveClass`.
```javascript
export default {
  router: {
    linkExactActiveClass: 'text-primary' // tailwind class with custom color
  }
}
```
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/x91cb493ecgjse2ovzzt.png)

Although adding your tailwind class to the config is a great method it will cause you problems if you don't want all your active links across all pages to be that colour. If you want more control then you should use the default class name or a custom one and use scoped styling. 

And that is all there is to it. If you don't already have your active links styled then go ahead and add a class for them. 

See the [nuxt docs](https://nuxtjs.org/api/configuration-router#linkactiveclass) for more info on the active and exact active classes.
Some Musings about Embedded Application Development
Tags: embedded, development
Published: 2020-04-22 14:13:51

---
title: Some Musings about Embedded Application Development
published: true
description: by Bill Churchill
tags: embedded, development
---
**Originally Published: 2015 July 12**

With the ubiquity of ARM processors and *nix distributions running on them, embedded application development more closely resembles desktop or server application development. No longer is it mandated that an application be their own operating system. Anyone who has done application development in a *nix environment can develop for an embedded linux appliance. However, there are some significant differences that change the approach of development in these environments. Right after application design, hardware constraints dominate a developer's thoughts.

An embedded device would have a limited number of processes running at any one time and each must be a good team player. No single application can monopolize any resource on the device. Using a smart phone as an example, if you have an application take up all the memory or processing cycles, the other applications will cease to perform in a responsive manner. You may not even be able to make calls or text until a reboot clears the problem.

Memory is a major limitation. In a PC environment, one typically has ample memory. Even when this is not the case, you still have the option of upgrading the memory. While it may be possible to run a memory managed vm like Java on your device, your performance can vary greatly. Typically, the choice of languages for a new application will be closer to the metal (C or C++). This allows finer grained control over memory allocation. Embedded applications usually grab any memory it would need at startup. This prevents out of memory exceptions or application halts for garbage collection (if a managed environment is used). These types of errors can hide during development and QA but rear its ugly head in the field.

While SD cards are growing in capacity, the root disk space is still very limited. Often the SD card is not used, as EPROM may be preferred. Small, tight libraries are extremely important in this type of development. The ubiquity of BusyBox on embedded devices illustrates this. Even within the application code, keeping things small and simple is important. Many systems load the entire root filesystem into memory. Another side benefit of using small libraries is the inherent small memory footprint when the application is loaded.

This is by no means an all inclusive list. Hopefully it will assist any developers looking to make the leap to embedded development. As phones become more sophisticated and wearables become more common, now is a good time to look at embedded application development for fun and/or profit.
Font Awesome Now Includes Social Distancing Icons
Tags: svg, fontawesome, icons
Published: 2020-04-22 13:52:32

The newest version of font awesome has been released and with it comes some new social distancing icons including, a "bacteria", "hands-wash", "no-handshake" and my personal fave "head-side-mask"

Whats your opinion on this? has anyone request anything like this as of yet?

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/07o2seur01v9pe1iijk9.png)