teleren/devto huggingface dataset:
Freezing Arrays in Javascript
Tags: javascript
Published: 2021-08-19 06:05:39

---
title: Freezing Arrays in Javascript
published: true
description: Javascript code snippet to freeze array
tags: javascript
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qknsxrxpe0ir7exok3uz.png
---

This is a cool tip recently tweeted by Oliver Jumpertz:
<blockquote class="twitter-tweet"><p lang="en" dir="ltr">💛 JavaScript tips 💛<br><br>Arrays are objects. Object.freeze has an effect on them.<br><br>This means that you can also make your arrays immutable. ↓ <a href="https://t.co/9stpcnRX8k">pic.twitter.com/9stpcnRX8k</a></p>&mdash; Oliver Jumpertz (@oliverjumpertz) <a href="https://twitter.com/oliverjumpertz/status/1428050011078680582?ref_src=twsrc%5Etfw">August 18, 2021</a></blockquote> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>

Having never used this in my code, I decided to give it a try and see what happens if I try to push an already frozen array.

So this is what I wrote in my Javascript file:
```
var desserts = ['chocolate', 'muffin', 'ice-cream']
console.log(desserts)
console.log(desserts.length)
desserts.push('brownie')
console.log(desserts)
console.log(desserts.length)

Object.freeze(desserts)

desserts.push('popsicle')
console.log(desserts)
console.log(desserts.length)
```
And this is the outcome:
```
[ 'chocolate', 'muffin', 'ice-cream' ]
3
[ 'chocolate', 'muffin', 'ice-cream', 'brownie' ]
4
```
And once you freeze it, you will get a runtime TypeError:

```
desserts.push('popsicle')
         ^

TypeError: Cannot add property 4, object is not extensible
    at Array.push (<anonymous>)
    at Object.<anonymous> (C:\repo\blog\js-freeze-array\freeze.js:10:10)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
    at internal/main/run_main_module.js:17:47
```

That's good to know, no?

Oh and if you haven't, please follow [Oliver on twitter.](https://twitter.com/oliverjumpertz/status/1428050011078680582) He shares a lot of tips like this.

Cover image by: https://pixabay.com/illustrations/christmas-background-landscape-4701783/
Save files with Apollo Server and React JS in 3 steps
Tags: apollo, react, express, nelsoncode
Published: 2021-08-19 05:58:50

### 1. Backend with Express and Apollo Server

```javascript
const express = require("express");
const { ApolloServer, gql } = require("apollo-server-express");
const app = express();
const { createWriteStream } = require("fs");
const cors = require("cors");

app.use(cors());

const typeDefs = gql`
  type Query {
    welcome: String
  }
  type Mutation {
    singleUpload(file: Upload): String
  }
`;

const saveImagesWithStream = ({ filename, mimetype, stream }) => {
  const path = `images/${filename}`;
  return new Promise((resolve, reject) =>
    stream
      .pipe(createWriteStream(path))
      .on("finish", () => resolve({ path, filename, mimetype }))
      .on("error", reject)
  );
};
const resolvers = {
  Query: {
    welcome: () => "Hello";
  },
  Mutation: {
    singleUpload: async (_, args) => {
      const { filename, mimetype, createReadStream } = await args.file;
      const stream = createReadStream();
      await saveImagesWithStream({ filename, mimetype, stream });
      return "success";
    },
  },
};

const server = new ApolloServer({ typeDefs: typeDefs, resolvers: resolvers });

server.applyMiddleware({ app });

app.listen({ port: 4000 }, () => console.log(`http://localhost:4000${server.graphqlPath}`));
```

### 2. Setup Apollo Upload Client

```javascript
import { ApolloProvider } from "@apollo/client";
import { client } from "./graphql/ApolloClient";
import { ApolloClient, InMemoryCache } from "@apollo/client";
import { createUploadLink } from "apollo-upload-client";

function App() {
const link = createUploadLink({ uri: "http://localhost:4000/graphql" });

const client = new ApolloClient({
  link,
  cache: new InMemoryCache(),
});
  return (
    <div>
      <ApolloProvider client={client}>
        <h1>Hello</h1>
      </ApolloProvider>
    </div>
  );
}

export default App;
```
### 3. Send Image with Apollo Client

```jsx
import React, { useState } from "react";
import { useMutation, gql } from "@apollo/client";

function UploadImages() {
  const [newImage, setnewImage] = useState(null);
  const [uploadImage, { data }] = useMutation(gql`
    mutation singleUpload($file: Upload) {
      singleUpload(file: $file)
    }
  `);
  console.log(data);
  return (
    <div>
      <input type="file" onChange={(e) => setnewImage(e.target.files[0])} />
      <button
        onClick={() => {
          uploadImage({
            variables: {
              file: newImage,
            },
          });
        }}
      >
        SEND IMAGE
      </button>
    </div>
  );
}

export default UploadImages;
```

[Code of example in Github 🔗](https://github.com/NelsonCode/save-files-express-react-graphql)
How to create Middlewares with FastAPI
Tags: fastapi, middleware, python, nelsoncode
Published: 2021-08-19 05:46:00

### ¿how do i add custom middleware?

```python
from fastapi import FastAPI, Request
from starlette.responses import JSONResponse, Response

app = FastAPI()

@app.middleware("http")
async def verify_user_agent(request: Request, call_next):
    if request.headers['User-Agent'].find("Mobile") == -1:
        response = await call_next(request)
        return response
    else:
        return JSONResponse(content={
            "message": "we do not allow mobiles"
        }, status_code=401)


@app.get('/')
def index(request: Request, response: Response):
    return {'message': 'ok'}
```
#### Default middlewares in FastAPI

* CORS
https://fastapi.tiangolo.com/tutorial/cors/
* GZIP
https://fastapi.tiangolo.com/advanced/middleware/#gzipmiddleware
* HTTPS REDIRECT https://fastapi.tiangolo.com/advanced/middleware/#httpsredirectmiddleware
* TRUSTED HOST
https://fastapi.tiangolo.com/advanced/middleware/#trustedhostmiddleware

¿How to add CORS with FastAPI ?

```python
from fastapi import FastAPI, Request
from starlette.responses import Response
from fastapi.middleware.wsgi import CORSMiddleware

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
@app.get('/')
def index(request: Request, response: Response):
    return {'message': 'ok'}
```
how to use react-router-dom, but better !!
Tags: react, reactrouterdom, betterreactrouterdom, router
Published: 2021-08-19 05:33:17

`1st step`
  //create react app like this ==> npx create-react-app react-router-dom

`2nd step` 
 //instal react-router-dom ==> npm i react-router-dom or yarn add react-router-dom

and then open your text editor like 'sublime text 4',

//3rd step

create file named as 'src/Navbar.js',
and use this code.
```
import React from 'react'
import {Link} from 'react-router-dom'

const Navbar = () => {
	return (
		<div>
			<Link to="/">Home</Link>
			<Link to="/about">About</Link>
		</div>
	)
}

export default Navbar
```

create your pages like "Home ,ABout,Contact etc" I am just gonna go with "Home and About" ok :).

this is my home and about code 
home :
```
import React from 'react'

const Home = () => {
	return (
		<div>
			<h1>This Is home page</h1>
		</div>
	)
}

export default Home
```
and this is for about :
```
import React from 'react'

const Home = () => {
	return (
		<div>
			<h1>This Is about page</h1>
		</div>
	)
}

export default Home
```
`last step`
//you have paste this code in app.js
```
import logo from './logo.svg';
import {BrowserRouter as Br,Route} from 'react-router-dom'
import Navbar from './Navbar'
import Home from './Home'
import About from './About'

function App() {
  return (
    <div className="App">
      
      <Br>
        <Navbar />
        <Route exact path="/">
        <Home />
      </Route>
      <Route exact path="/about">
        <About />
      </Route>
      </Br>
    </div>
  );
}

export default App;

```
[Part 2] Executing batch jobs in a multi-container environment using NodeJS and express.
Tags: node, redis, javascript, docker
Published: 2021-08-19 05:19:30

## Create a CRON job to be executed at 12 am every day

In this step, we will register a CRON job that executes at 12 am every day. This CRON job will simply console log the time of execution and a static message. 

**Step 1**

Add a new `QUEUE_NAME` called **MIDNIGHT_CRON**

```
export const QUEUE_NAMES = {
  SCHEDULE_JOB: 'scheduleJob',
  MIDNIGHT_CRON: 'midnightCron'
};
```

**Step 2**

Add a new processor for `CRON`

```
const CRON_EXPRESSIONS = {
  MIDNIGHT: '0 0 * * *'
};

export const QUEUE_PROCESSORS = {
   ...,
  [QUEUE_NAMES.MIDNIGHT_CRON]: (job, done) => {
		console.log({ job, done });
    console.log(`${moment()}::The MIDNIGHT_CRON is being executed at 12:00am`);
    done();
  }
};
```

**Step 3**

Register the CRON job in the **server/utils/queue.js**

```
export const initQueues = () => {
  ...
  queues[QUEUE_NAMES.MIDNIGHT_CRON].add({}, { repeat: { cron: CRON_EXPRESSIONS.MIDNIGHT } });
};
```

We will invoke the `initQueues` method from the `server/index.js` to initialize the queues on startup. After initializing the queues we will add a CRON job to be executed at 12 am.

You should see the below logs at 12 am! Feel free to update the regex and execute the CRON sooner than 12 am to test how it works.

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

Commit your code using the following git commands

```
git add .
git commit -m 'Add support to run a CRON job at 12 AM everyday'
```

## Where to go from here

You now have the ability to set up CRON jobs in a multi-container environment.

I hope you enjoyed reading this article as much as I enjoyed writing it. If this peaked your interest stay tuned for the next article in the series where I will take you through how to write GraphQL subscriptions in a multi-container environment using  `graphql-redis-subscriptions`

If you have any questions or comments, please join the forum discussion below.

➤This blog was originally posted on https://wednesday.is To know more about what it’s like to work with Wednesday follow us on: [Instagram](https://www.instagram.com/wednesday.sol/)|[Twitter](https://twitter.com/wednesdaysol)|[LinkedIn](https://www.linkedin.com/company/wednesday-solutions)
Grouping Multiple Resources in Blazor Scheduler
Tags: webdev, blazor, csharp, dotnet
Published: 2021-08-19 05:14:31

Get a quick overview of grouping multiple resources in [Blazor Scheduler](https://www.syncfusion.com/blazor-components/blazor-scheduler). 

To find out how to add a basic Blazor Scheduler to your Blazor application, watch these videos:

 Add a Blazor Scheduler to the Blazor Server App Using VS Code https://bit.ly/3uPalCi 

Bind Appointment Data to the Blazor Scheduler [Getting Started - Part 2] https://bit.ly/3yRGXxv I

n this video, you will learn how to group multiple resources and to define the group data source, and map it with appointments. You will also learn how to group resources under dates and group the resources hierarchically in the Blazor Scheduler.

 Explore our tutorial videos: https://bit.ly/2VZaDd6

 Download example from GitHub link: https://bit.ly/2U2P9eZ

{% youtube 70qD6wycxAk %}
Common Lisp - Log 1 (set up)
Tags: programming
Published: 2021-08-19 04:45:09

I'm not going to lie, setting up emacs for lisp is far easier than any tutorial that i've wasted hours trying to figure out. So much time wasted, spending time trying to edit .emacs files outside of emacs; I found my own, much easier way of configuring this.

Already knowing that emacs comes with its own eshell for managing files and stuff inside of emacs (as well as a shell for managing files on your device,) and since I am a mac user, I simply installed homebrew on emacs eshell; and from there, it was cake to brew install clisp and sbcl repl's from eshell.

Next, we back out of emacs, and download the slime package from the web page, which took just a quick google search to find.

Now, again, we break out that emacs and use M-x, package install slime, then restart (doom, for me) emacs.

Now, using M-x, enter slime and you are ready to go with three powerful repls, for maximum coding performance for emacs lisp.

Whoever said emacs is too confusing to be worth learning is a liar; best learning curve i've overcome - the payoff is awesome.
Create a Netflix clone from Scratch: JavaScript PHP + MySQL Day 24
Tags: php, javascript, tutorial, webdev
Published: 2021-08-19 04:30:56

Netflix provides streaming movies and TV shows to over 75 million subscribers across
the globe. Customers can watch as many shows/ movies as they want as long as they are
connected to the internet for a monthly subscription fee of about ten dollars. Netflix produces
original content and also pays for the rights to stream feature films and shows.


In this video,we will be creating a method to generate verification code

{% youtube ibVGv6cJw9M %}

In this video,we will be creating the verification table

{% youtube B1opMzzgYSI %}

If you like my work, please consider
[![Buy me a coffee](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jm11knj7d8zwcvo150q2.png)](https://www.buymeacoffee.com/cglikpo)
so that I can bring more projects, more articles for you

If you want to learn more about Web Development, feel free to [follow me on Youtube!](https://www.youtube.com/c/ChristopherGlikpo)
My Cloud Resume Challenge Journey
Published: 2021-08-19 01:38:00

This summer, I learned how to use Amazon Web Services. I studied to get my Cloud Practitioner cert, but to do well in a real cloud job, it is not enough to be able to pass a test: you must truly understand how to use and synchronize different cloud services. Because of this, I decided to complete Forrest Brazeal’s Cloud Resume Challenge.

I had just graduated from the University of Minnesota with my math degree. My classes were challenging and taught me a lot, but I had never built a website or done much coding before. In my classes I had learned basic C++ and SQL, but for this challenge I had to learn HTML, CSS, and JS for the front end, SAM, JSON and Python for the backend, and GitHub Actions for CI/CD.  This was a completely different experience from solving problems at school.  

The aspect that took the longest was debugging the whole thing. In this particular app, the hardest part is not the theory at all but just figuring out how everything works and just as importantly seeing what doesn’t. One recurring problem was the compatibility of different services with the API: I had to enable CORS for my API so that my website could call it and turn a Decimal output of my Lambda function into an integer that was readable by the API. It's vital to be able to understand how all the different packages and programs all fit together. SAM does a great job at integrating it all.

This has been a great learning experience for me. Before, I had no experience with any sort of development or IT, now I can do full-stack web app development and implement tech solutions in the cloud. Hopefully I can get my foot in the door soon and put my new knowledge into practice.
Icons for your next project.
Tags: javascript, codenewbie, webdev, productivity
Published: 2021-08-19 03:42:26

Hello All, Today I am here to mention some free sites from where you can choose the Icons for your next project :)

Personal Choice -

1. Flat Icon - https://www.flaticon.com/
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1cd86ffghk6khuxfafj2.png)
 
2. Icons8 - https://icons8.com/
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5ydg62ligzoejfwzc1lt.png)

3. FreePik - https://www.freepik.com/
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6y5gxenhov09e2jqlc1c.png)

4. Material Icons - https://fonts.google.com/icons
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pr7y82qdt2gjahdlwkqe.png)
   

Others -
- https://iconstore.co/
- https://iconmonstr.com/
- https://dryicons.com/
- https://freeicons.io/
- https://fontawesome.com/
- https://streamlinehq.com/
- https://graphicburger.com/icons-set/
- http://www.pixeden.com/icons-set
- https://www.iconfinder.com/
- https://www.iconshock.com/free-icons/
- https://pngtree.com/so/icon
How to extract text and image from a PowerPoint Document in Java
Tags: text, image, extract, pptx
Published: 2021-08-19 03:29:33

---
title: How to extract text and image from a PowerPoint Document in Java
published: true
description: extract text from slides, extract image from powerpoint
tags: text, image, extract, pptx
//cover_image: https://direct_url_to_image.jpg
---
Texts and images are the main elements on the Presentation slides. In this article, we will show you how to extract text and image from a PowerPoint document using Free Spire.Presentation for Java.

Installation

If you use maven, you need to specify the dependencies for Free Spire.Presentation for Java library in your project’s pom.xml file.

```code
<repositories>  
        <repository>  
            <id>com.e-iceblue</id>  
            <name>e-iceblue</name>  
            <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>  
        </repository>  
</repositories>  
<dependencies>  
    <dependency>  
        <groupId>e-iceblue</groupId>  
        <artifactId>spire.presentation.free</artifactId>  
        <version>3.9.0</version>  
    </dependency>  
</dependencies>
```

For non-maven projects, download [Free Spire.Presentation for Java](https://www.e-iceblue.com/Download/presentation-for-java-free.html), unzip the package and add Spire.Presentation.jar in the lib folder into your project as a dependency.

```java
import com.spire.presentation.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileWriter;

public class Test {
    public static void main(String[] args) throws Exception {
        //Create a presentation instance.
        Presentation ppt = new Presentation();

        // Load the document from disk.
        ppt.loadFromFile("Sample.pptx");

            StringBuilder buffer = new StringBuilder();
            //Traverse the presentation slides to extract the text.
            for (Object slide : ppt.getSlides()) {
                for (Object shape : ((ISlide) slide).getShapes()) {
                    if (shape instanceof IAutoShape) {
                        for (Object tp : ((IAutoShape) shape).getTextFrame().getParagraphs()) {
                            buffer.append(((ParagraphEx) tp).getText());
                        }
                    }
                }
            }
            //Save to document to .txt
            FileWriter writer = new FileWriter("ExtractText.txt");
            writer.write(buffer.toString());
            writer.flush();
            writer.close();

        //Extract all the images from the presentation slides
        for (int i = 0; i < ppt.getImages().getCount(); i++) {
            BufferedImage image = ppt.getImages().get(i).getImage();
            ImageIO.write(image, "PNG", new File(String.format("extractImage-%1$s.png", i)));
        }
    }
}
```
The effective screenshot of the extracted images:
 ![Extracted images](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/98asx18glvfn745pchwt.png)

![Extracted Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8se8u3hp6yboqa9wq1ag.png)
When NOT to use Amazon Sagemaker
Tags: aws, amazon, machinelearning, beginners
Published: 2021-08-19 03:14:09

Hey Friends :hand:
So I hope you liked my previous article on why we can move towards Amazon Sagemaker, but as they say, you can use sugar everywhere.
Similarly, in this article we are going to discuss some scenarios, where we can NOT use Amazon Sagemaker. Or I should rephrase it as where Amazon Sagemaker won't be a viable option.

The problems we discussed in the past article though represent a vast majority of ML projects, there are certainly few scenarios where this might not be a valid option. 

## Scenarios

1. Sagemaker, expects you to code your data engineering and analysis needs(in your choice of language). 
2. The entire orchestration of infrastructure and transition from one phase to another though happens with few lines code; definitely needs a small amount of code. 
3. For professionals, who prefer a drag and drop (absolutely no code) solutions for the data engineering and modeling phase, Azure ML studio would be a more ideal choice. 
4. Both Azure ML Studio and AWS Sagemaker are great platforms for developing ML solutions but are targetted for a completely different set of users. 

## Conclusions

AWS Sagemaker has been a great deal for most data scientists who would want to accomplish a truly end-to-end ML solution. It takes care of abstracting a ton of software development skills necessary to accomplish the task while still being highly effective and flexible and cost-effective. Most importantly, it helps you focus on the core ML experiments and supplements the remainder necessary skills with easy abstracted tools similar to our existing workflow.
Finding a Sense of Impact in Web Development
Published: 2021-08-19 02:02:42

> How does one align themselves with projects that speak to their core beliefs? Is it naïve to think this kind of balance exists, or that it is achievable while working for someone other than oneself?

*Whew. This is a tough one for me.*

For some context, I work at an advertising agency that specializes in high-visibility, "boutique" digital experiences. That is to say, high-budget websites. I am a Senior Developer focused on frontend development, working alongside ~8 other developers with varying specializations and backgrounds.

But back to the topic at hand: how do I find a sense of positive impact? Positive impact on the agency I work for; positive impact on the clientele for a given project; positive impact even on the world?

I occasionally have the privilege of working on a project with noble aspirations; a desire to address the injustices of the world. This is rare. Most often, I feel at-odds with the values that many clients bring to the table, and in turn I feel at-odds with contributing to their success.

From private equity firms run by old-money millionaires, to exorbitantly priced hotels, retreats or resorts, there is a distinct impression that these companies and organizations do not exist to better our planet or society, but instead exist chiefly to turn a profit from those with disposable income to spare.

To further complicate things, these projects stand in stark contrast with the immense joy and fulfillment I feel when helping fellow team members. Whether it is through building a new technology or tool that improves their day-to-day life; through teaching and mentoring; or by advocating for a teammate, this kind of work is at the core of what I feel to be impactful.

When the cards fall in such a way that my chief responsibility for given project is not "build the site so the client is happy, don't think too much about the company behind the curtain", I come alive with a sense of pride and belief that my work is creating the impact this company value speaks to. In other contexts, this is not so much the case.

But it is still such a mystery to me... These questions have been keeping me up at night lately.

And so I'm writing this to see if there are others out there who feel the same way; who have the same questions or perhaps have walked this path before. What are your solutions, your technologies, your mindsets? I would love to know how you find a sense of impact in the vast landscape of web development.

Please leave a comment if you have thoughts you would like to share. You can also [find me on Twitter as @aaronransley](https://twitter.com/aaronransley), or [shoot me an email](mailto:me@aaronransley.com).

Impactfully,
Aaron