teleren/devto huggingface dataset:
CSP Gotchas vol. 1
Tags: contentsecuritypolicy, webapplication, javascript
Published: 2021-04-09 03:51:01

---
title: CSP Gotchas vol. 1
published: true
description: Looking at the nuance of 'strict-dynamic' in CSP
tags: ContentSecurityPolicy, WebApplication, JavaScript
cover_image: https://www.fastcomet.com/blog/wp-content/uploads/2018/10/content-security-policies.jpg
---

TLDR; Today's lesson in Content Security Policy: using a nonce or hash to allowlist a script does not allow that script to use 'javascript: urls', inline event handlers, or eval.

Today I had the opportunity to review how the Content Security Policy was working for a web application that I work on. I thought it was pretty locked down after implementing a nonce based strategy a few months ago. My assumption with using nonces was that the allowed script would be given free rein to do whatever it wanted in the browser. After all, it seemed like the nonce was telling the browser that the script was implicitly trusted.

Also, the description of 'strict-dynamic' in the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src) on the script-src directive is a little vague, simply saying: 

>The strict-dynamic source expression specifies that the trust explicitly given to a script present in the markup, by accompanying it with a nonce or a hash, shall be propagated to all the scripts loaded by that root script. At the same time, any allow-list or source expressions such as 'self' or 'unsafe-inline' are ignored.

When it says that 'unsafe-inline' is ignored, I read that to mean that 'unsafe-inline' would be redundant when used in tandem with 'strict-dynamic' (at least for the scripts using the nonce). In reality though, 'strict-dynamic' blocks 'javascript: urls' and inline event handlers where 'unsafe-inline' does not.

I only learned this after an hour of scouring the internet for explanations as to why certain scripts loading on my site were still throwing CSP errors even though they contained the nonce attribute. I finally found [this comment](https://bugzilla.mozilla.org/show_bug.cgi?id=1004703) on bugzilla from six years ago that pointed me to the issue:

> ...if you use a nonce/hash it's not possible to use javascript: urls or inline event handlers. It's as if the policy didn't have unsafe-inline at all...

That's when I decided to try adding an 'unsafe-eval' to the script-src in my policy in addition to 'strict-dynamic' with a nonce to see if the 'eval' errors would go away. They did. BUT, as the bugzilla post referenced above also points out, you can't do this for 'unsafe-inline'. You can either use 'strict-dynamic' OR 'unsafe-inline', but you can't get the best of both worlds.

The intricacies and complexities of building a robust Content Security Policy for the modern web (especially while dealing with legacy dependencies) never ceases to amaze me!
I've Recently Learned About GPT3 - This is my Journey
Tags: gpt3, webdev, ai, oop
Published: 2021-04-09 03:11:46

I've been very excited since GPT-3 release almost a year ago.

I applied early for closed beta, but had no news so far.

The product is nowadays controlled by Microsoft, and they are gatekeeping it to avoid unethical uses (and avoid [past mistakes](https://en.wikipedia.org/wiki/Tay_(bot) ).

I've read some very interesting articles related to GPT-3:

[The Latest AI Model](https://anujsyal.com/gpt-3-the-latest-language-model-in-ai-c8634a314911)

... and made some theoretical courses on it 

[Linkedin Learning](https://www.linkedin.com/learning/introduction-to-gpt-3-a-leap-in-artificial-intelligence/gpt-3-the-next-leap-in-ai)

By now, GPT-3 is closer to [narrow artificial intelligence](https://en.wikipedia.org/wiki/Weak_AI) than [Artificial General intelligence](https://en.wikipedia.org/wiki/Artificial_general_intelligence). But it is a very successful narrow transformer deceiving humans for long time periods.

# State of the art

There are not many GPT-3 Implementations due to being on closed beta. 

There's an incipient app marketplace

[GPT-3 Demo](https://gpt3demo.com/)

Hopefully it will grow soon.

# Moving forward

I've been thinking a lot about transformers and generators applied to programming.

Most code generators I've tested are too dumb. They can program very basic routines and are not yet able to create [great software designs](https://dev.to/mcsee/what-is-wrong-with-software-5pa).

{% youtube fZSFNUT6iY8 %}

In my Code Smell Series, I suggest detection techniques and correction measures. 

{% post https://dev.to/mcsee/code-smell-01-anemic-models-4dg2 %}

Some of them involve just syntactic manipulations most actual linters can do.

But, many of them require pattern recognition and some added intelligence. 

**I am anxious to build a GPT3 solution to assist programmers and made code reviews.**

What do you think? Will we be using them in the near future?

Tell me in the comments below...
How do I check if a file exists?
Tags: android, java
Published: 2021-04-09 03:09:07

How do I check if a file exists in my android app? I am using the following code:

File file = new file(android.os.Environment.DIRECTORY_PICTURES)+ ("/img_map/map1.jpg");
		if(file.exists()){ //do something
		} else{//do something else
		}
PHP Laravel 8 Inner Join Query Example
Tags: laravel, mysql
Published: 2021-04-09 02:44:44

Hello Dev’s 
Today I will give you a short example of how to use inner join on query builder in laravel 8 project.We know here how to PHP Laravel 8 Inner Join work.
Read more: 
https://codingspoint.com/php-laravel-8-inner-join-query-example/
MERN Stack BoilerPlate with two type auth
Tags: react, node, mongodb, express
Published: 2021-04-09 02:34:01

Are you looking forward a Mern stack boilerplate with admin role and regular user auth included? This is the boilerplate for you!

[Git Repo](https://github.com/alaminsheikh01/MERN-boilerPlate)

## Techonologies

- MongoDb and Mongoose - MongoDb as a Database and mongoose as as a Object Data - Modeling library for MongoDB and Node.js
- Express - as a backend Framework
- React - as a Frontend Framework
- Node - as a Server
- Redux - for state Management (will be updated)
- JsonWebToken - for creating JSON-based access tokens
- bcryptjs - for hashing the user passwords

also two type of role one is admin role and another one is user role
when user or admin as a login then there data will save in the localStorage.

Feel free to give me some suggestions to improve it!
Happy coding to everyone!
Unity Debug Print
Tags: unity3d, ugui, debug
Published: 2021-04-09 02:15:41

---
title: Unity Debug Print
published: true
description: My snippet for debugging unity project.
tags: unity,ugui,debug
//cover_image: https://direct_url_to_image.jpg
---
```
using UnityEngine;
using System.Text;

#region Debug Print

[SerializeField]
private Text DebugText; // for UnityEngine.UI.Text

private void PrintDebug( string s, bool showTime = true)
{
    if(DebugText != null)
    {
        StringBuilder sb = new StringBuilder();
        if (showTime)
        {
            sb.Append(System.DateTime.Now.ToString("[HH:mm:ss] "));
        }
        sb.AppendLine(s);
        sb.AppendLine(DebugText.text);

        DebugText.text = sb.ToString();
    }
}


#endregion / Debug Print
```
FactoryBot sidecar associations
Published: 2021-04-09 02:06:00

# The problem

Often, we create "sidecar" models alongside "primary" models in Rails apps. For instance, if you're developing a blogging platform, you may want to create the user's blog model when the user signs up. An example set of models:

```rb
class User
  has_one :blog
end

class Blog
  belongs_to :user
end

class UserCreationService
  def self.call(user_attrs:)
    user = User.create(user_attrs)
    Blog.create(user: user)
  end
end
```

This works great in production, since we always run that service when users are created. However, when testing we might not want to use the service in every spec that requires a user. This is where a fixture/factory setup comes in.

Now, when testing your app in RSpec, I've found the ease of building models with FactoryBot to be a much better development experience than using Rails' standard fixtures. To build a factory for these, you might do something like this to start:

```rb
FactoryBot.define do
  factory :user do
    blog
  end

  factory :blog do
    user
  end
end
```

Then, in your model specs:

```b
describe User do
  subject { build(:user) }
  it { is_expected.to be_valid } # i.e. have a valid factory
end

describe Blog do
  subject { build(:blog) }
  it { is_expected.to be_valid }
end
```

However, running these specs will give you an error like this:

```rb
SystemStackError:
  stack level too deep
```

This happens because FactoryBot doesn't know that, when calling `build(:user)`, (which calls `build(:blog)`), that the user is already present to be attached. Therefore `build(:blog)` will just call `build(:user)`, and so on, creating the infinite loop.

# The Solution

To fix this, we need to specifically assign the sidecar model to the primary, and vice versa, in the factories:

```rb
FactoryBot.define do
  factory :user do
    blog { association :blog, user: instance }
  end

  factory :blog do
    user { association :user, blog: instance }
  end
end
```

This will properly associate the 1-1 models whether you call `build(:user)` or `build(:blog)`. You can even still use an override attribute to create a model with override attributes.

```rb
2 examples, 0 failures
```

Hopefully this helps. This should be one of many tiny tidbits.
My first API using native PHP
Tags: php, api, codenewbie
Published: 2021-04-09 01:49:07

I tried to create my first API while exercising OOP using php, and here what I achieved, [take live look here!](https://egypt-museums-api.000webhostapp.com/api/read.php)

###First things First!
I created env.php which includes `class Environment` to parse my own .env file through `public function getDatabaseVariables()` in order to capture database variables 
```bash
#Database#
HOST = "localhost"
DATABASE_SERVICE = "mysql"
DATABASE_NAME = "example_db"
DATABASE_USERNAME = "example_user"
DATABASE_PASSWORD = "example_password"
```

I followed the below approach to parse .env file using preg_match to detect the first line.
```php 
$validate_line_from_env_file = preg_match('~^[a-zA-Z]~',$line);
```

then make use of `explode` and `strpos` to catch variable in an associative array as following:
```php
$env_file_text = explode('= "',$line);
$env_variable_key_length = strpos($env_file_text[0]," ");
$env_variable_key = substr($env_file_text[0],0,$env_variable_key_length);
$env_variable_value_length = strpos($env_file_text[1],"\"");
$env_variable_value = substr($env_file_text[1],0,$env_variable_value_length);
if ($env_variable_value == true)
{
	$this->variables += [$env_variable_key => $env_variable_value];
}
else if ($env_variable_value === "")
{
	$this->variables += [$env_variable_key => ""];
}
```



**Then** those variables are passed to `class Database` that extends `class Environment` where the `__construct()` function store the required variables, after that a database connection will be created using `PDO`.

###Query the items
The database connection function is being called through `__construct()` function of `class Museum`, where the query statement exists

```php
public function getMuseums()
{
	$sqlQuery = "SELECT id, mname, arabic_name, city, type, est_year, website, coordinates, wikipedia_url FROM " . $this->db_table;
	$statement = $this->conn->prepare($sqlQuery);
	$statement->execute();
	return $statement;

}
```

##Finally!
query is being executed in read.php which present api result in json format.
```php
$statement = $items->getMuseums();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
$itemCount = $statement->rowCount();

//prepare array for json format
if ($itemCount > 0){
	$museumArray = array();
	$museumArray["itemCount"] = $itemCount;
	$museumArray["body"] = $result;

	echo json_encode($museumArray);
}
else
{
http_response_code(404);
echo json_encode(
	array("message" => "No record found.")
);
```

**last piece**: I added the following .htaccess code to prevent accessing other routes except .api/read.php

```xml
Order deny,allow
Deny from all

<Files "read.php">
    Allow from all
</Files>
```

###Output sample
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/say1ep6ze08kayqazf73.PNG)

####You can check this api
on [github](https://github.com/theahmedlatif/egypt_museums_api)
or [visit the live version](https://egypt-museums-api.000webhostapp.com/api/read.php)
___
Thanks for your time reading my article!
Load a PDF Embed when Visible
Tags: adobe, pdfservices, javascript, development
Published: 2021-07-12 21:28:40

---
title: Load a PDF Embed when Visible
published: true
date: 2021-04-09 00:00:00 UTC
tags: adobe,pdfservices,javascript,development
canonical_url: https://www.raymondcamden.com/2021/04/09/load-a-pdf-embed-when-visible
---

A quick tip before I turn my brain off for the weekend (that's not entirely true, tonight I plan on building LEGO). I've blogged before about the [PDF Embed API](https://www.adobe.io/apis/documentcloud/dcsdk/pdf-embed.html), it's one of the tools my new job involves. If you didn't see my first post on it, definitely give it a quick read: [Using the PDF Embed API with Vue.js](https://www.raymondcamden.com/2021/02/17/using-the-pdf-embed-api-with-vuejs) Today's tip is a bit simpler - how can we use the PDF Embed API to only load a PDF once it's actually visible in the DOM?

Turns out it's rather simple. Modern browsers support the [Intersection Observer API](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API). When I say "modern browsers", I mean all but Safari, but they're working on it. You can find more details at CanIUse: [https://caniuse.com/intersectionobserver](https://caniuse.com/intersectionobserver).

I thought I'd do a quick demo of using the PDF Embed API and Intersection Observer together. Turns out it was incredibly simple:

```js
const ADOBE_KEY = 'b9151e8d6a0b4d798e0f8d7950efea91';

if(!!window.IntersectionObserver) {
	const pdfBox = document.querySelector('#pdfArea');

	const intersectionObserver = new IntersectionObserver(function(entries, observer) {
		if(entries && entries[0] && entries[0].isIntersecting){
			loadPDF();
			observer.unobserve(pdfBox);
		}
	});
	intersectionObserver.observe(pdfBox);
} else loadPDF();

function loadPDF() {
	console.log('visible');
	const adobeDCView = new AdobeDC.View({
		clientId: ADOBE_KEY, 
		divId: "pdfArea"
	});
	adobeDCView.previewFile({
      content:{ 
				location: 
        { url: "https://documentcloud.adobe.com/view-sdk-demo/PDFs/Bodea%20Brochure.pdf" }
			},
      metaData:{ fileName: "Bodea Brochure.pdf"}
    },
    {
      embedMode: "SIZED_CONTAINER"
    });
}
```

Basically, if the browser supports the API, I set up an observer to monitor part of the DOM (see the earlier `querySelector`. When it detects that it's visible, I run `loadPDF`. If the API is not supported, I just run `loadPDF` immediately.

And that's it. I freaking love how simple that was. If you want to see a demo with some lovely [Cat Ipsum](https://fungenerators.com/lorem-ipsum/cat/), take a gander at the CodePen below.

See the Pen [PDF when Visible Test](https://codepen.io/cfjedimaster/pen/abpEmPd) by Raymond Camden ([@cfjedimaster](https://codepen.io/cfjedimaster)) on [CodePen](https://codepen.io).

<script async src="https://cpwebassets.codepen.io/assets/embed/ei.js"></script>

Photo by [Michael Dziedzic](https://unsplash.com/@lazycreekimages?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/s/photos/invisible?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)
Private Docker Repository
Tags: docker
Published: 2021-04-09 01:17:56

The [normal way to setup a private Docker repository](https://docs.docker.com/registry/deploying/) is to simply use the container which has it all setup. This works really well for a lot of cases. I recently deployed a private repo where I need an implementation that was a bit easier to manage with existing tooling and infrastructure. Basically, this meant not running docker for the repo and integration with an existing authentication framework.

Instructions are CentOS 7 specific, but shouldn't be too hard to map to your distribution of choice.

nginx is used as a proxy to terminate TLS and handle the federated authentication, leaving the docker repository service running on localhost only. 

## Install

Repos: CentOS Extras, Docker-CE, (possibly EPEL)
Packages: docker-distribution, docker-ce, nginx

## Configure

### docker-distribution

I only customized the rootdirectory and http addr. See Docker's [documentation](https://docs.docker.com/registry/configuration/).
/etc/docker-distribution/registry/config.yml (select parts)

```yaml
version: 0.1
log:
  fields:
    service: registry
storage:
  cache:
    layerinfo: inmemory
  filesystem:
     rootdirectory: /path/to/storage/repo
http:
   addr: localhost:5000
```

### nginx

(Not including SSL and federated authentication)

/etc/nginx/conf.d/docker.conf

```nginx
server {
   server_name myrepo.mydomain;
   listen 443 ssl;
   # omit SSL directives here
   client_max_body_size 0;
   # This just has a simple HTML info page
   root /path/to/storage/docroot;
   index index.html;
   # proxy docker API
   location /v2 {
      proxy_set_header X-Forwarded-Host $host;
      proxy_set_header X-Forwarded-Server $host;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
      proxy_set_header Host myrepo.mydomain;
      proxy_pass http://localhost:5000;
   }
}
```

### docker

(This is optional. I use it to do local admin and some maintenance scripts.

/etc/docker/daemon.json

```json
{
   "data-root": "/path/to/storage/root"
}
```

## Run and Test

### docker-distribution

```bash
systemctl start docker-distribution
systemctl enable docker-distribution
```

#### Verify
```bash
curl http://localhost:5000/v2/_catalog
```
Should return an empty repository list
```json
{
   "repositories": []
}
```

### nginx

```bash
systemctl start nginx
systemctl enable nginx
```

#### Verify
```bash
curl https://myrepo.mydomain/
```
Should return whatever you put at /path/to/storage/docroot/index.html

```bash
curl https://myrepo.mydomain/v2/_catalog
```
Should return an empty repository list
```json
{
   "repositories": []
}
```

### docker

```bash
systemctl start docker
systemctl enable docker
```

#### Verify
```bash
docker info
```

Should return some information about your docker installation (including the customized root path).

------

You have now setup a local Docker repository which will work just like the docker container based one.
How to use 'effect' hook easy way
Tags: javascript, react
Published: 2021-04-09 00:53:18



### Hooks are additional in react 16.8, Hooks let us to use state and other React features without writing class wooow 😎
In previous post I was explained about `useState`, in this post I will explain about `useEffect`.
In sort `useEffect` let us perform side effect after we render component, let see example below.

#### Example using class component
```js
class PlusOne extends React.Component{
    // prepare and declaring state 
    constructor(props);
    super(props);
    this.state = {
        count:0
    }
    componentDidMount() {
        document.title = `hit ${this.state.count} times`;
    }
    componentDidUpdate() {
        document.title = `hit ${this.state.count} times`;
    }
    render() {
        return(
            <div>
                <p>you hit {this.state.count}</p>
                <button onClick={() => this.setState({ count: this.state.count + 1 })}>
                    +
                </button>
            </div>
        )
    }
}
```
#### Example function components using hooks

>   gently reminder that hooks doesn't work with class component 
```js
   // import useState and useEffect from react lib
   import React, { useState,useEffect } from 'react';
   function PlusOne() {
       const[count,setCount]= useState(0); /* first count variable value set to 0 */
       useEffect(()=>{
           /*
            use effect let us express side effect after component rendered.   
           */
           document.title = `hit ${count} times`; 
       },[count]) // only re-run effect if count changes
       return(
           <div>
            <p> you hit {count} </p>
            <button onClick={()=> setCount(count+1)}>
                +
            </button>
           </div>
       )
   }
```
PHP DamerauLevenshtein ALGORITHM
Tags: php
Published: 2021-04-09 00:43:07

/*
 * Naïve implementation of Damerau-Levenshtein distance
 * (Does not work when there are neighbouring transpositions)!
*/

```
  function DamerauLevenshtein($S1, $S2)
  {
    $L1 = strlen($S1);
    $L2 = strlen($S2);
    if ($L1==0 || $L2==0) {
        // Trivial case: one string is 0-length
        return max($L1, $L2);
    }
    else {
        // The cost of substituting the last character
        $substitutionCost = ($S1[$L1-1] != $S2[$L2-1])? 1 : 0;
        // {H1,H2} are {L1,L2} with the last character chopped off
        $H1 = substr($S1, 0, $L1-1);
        $H2 = substr($S2, 0, $L2-1);
        if ($L1>1 && $L2>1 && $S1[$L1-1]==$S2[$L2-2] && $S1[$L1-2]==$S2[$L2-1]) {
            return min (
                DamerauLevenshtein($H1, $S2) + 1,
                DamerauLevenshtein($S1, $H2) + 1,
                DamerauLevenshtein($H1, $H2) + $substitutionCost,
                DamerauLevenshtein(substr($S1, 0, $L1-2), substr($S2, 0, $L2-2)) + 1
            );
        }
        return min (
            DamerauLevenshtein($H1, $S2) + 1,
            DamerauLevenshtein($S1, $H2) + 1,
            DamerauLevenshtein($H1, $H2) + $substitutionCost
        );
    }
}
```
Introducing the GitHub Security Overview | GitHub Security Center
Tags: github, security, devops, devsecops
Published: 2021-04-09 00:03:35

The new GitHub Security Overview, commonly referred to as GitHub Security Center, consolidates in one place all the GitHub Advanced Security recommendations like the GitHub Code scanning results, the GitHub Secret Scanning, etc.

### Video

To showcase this important and long awaited new feature, I've create a video in which I go through how to access and how to use all the new features.

Watch the full video here 🤓

{% youtube ChDykZU5M9s %}

[Link to the video: https://youtu.be/ChDykZU5M9s](https://youtu.be/ChDykZU5M9s)

Let me know below what you think! Do you have any other questions about Linters and Linting? 

__Stay tuned__ because I will soon have another post and video about the __GitHub Super Linter__!

__Like, share and follow me__ 🚀 for more content:

📽 [YouTube](https://www.youtube.com/CoderDave)
☕ [Buy me a coffee](https://buymeacoffee.com/CoderDave)
💖 [Patreon](https://patreon.com/CoderDave)
👕 [Merch](https://geni.us/cdmerch)
👦🏻 [Facebook page](https://www.facebook.com/CoderDaveYT)
🐱‍💻 [GitHub](https://github.com/n3wt0n)
👲🏻 [Twitter](https://www.twitter.com/davide.benvegnu)
👴🏻 [LinkedIn](https://www.linkedin.com/in/davidebenvegnu/)
🔉 [Podcast](https://geni.us/cdpodcast)


{% youtube ChDykZU5M9s %}