teleren/devto huggingface dataset:
"lockfile" Module in Python, When and how to use that
Tags: python, programming, lockfile, tutorial
Published: 2023-02-17 17:58:35

The **lockfile** module in Python provides a simple way to lock files and ensure that only one process or thread can access the file at a time. This is useful for preventing race conditions and ensuring that multiple processes or threads don't interfere with each other.

#### To install lockfile

```bash
pip install lockfile
```

#### A Simple Example:

```python
import lockfile

lock = lockfile.FileLock("file.lock")

try:
    lock.acquire(timeout=10)
    # Access the file here
    with Open("file.txt", "w") as f:
        # Do your write operation
finally:
    lock.release()

```
Here, You can name your lockfile anything you want, in our case, it is **file.lock**. This file will temporally create while acquiring the lock and it will automatically deleted after releasing the lock.

#### Another example of how you can use the **lockfile** module to lock a file for a specific duration:

```python
import time
from lockfile import FileLock

lock = FileLock("file.lock")

with lock:
    # Access the file here
    with Open("file.txt", "w") as f:
        # Do your write operation
    time.sleep(10)

```


#### Another example (without **_lockfile_**) of how two Python scripts can write to the same file simultaneously and cause a race condition:


```python
# Script 1
with open("samefile.txt", "w") as f:
    for line in range(10):
        f.write(f"Script 1: Line {line} \n")

# Script 2
with open("samefile.txt", "w") as f:
    for line in range(10):
        f.write(f"Script 2: Line {line} \n")

```
Here, both scripts open the file **samefile.txt** using the **with** statement and write 10 lines of text to the file. However, since both scripts open the file in write mode (**"w"**), they overwrite each other's changes and only one set of lines is written to the file. This is an example of a race condition, as the outcome of the scripts depends on which one finishes first.

#### To prevent this race condition, you can use a lock file to ensure that only one script can write to the file at a time:

```python
import lockfile

# Script 1
lock = lockfile.FileLock("file.lock")
with lock:
    with open("samefile.txt", "a") as f:
        for line in range(10):
            f.write(f"Script 1: Line {line} \n")

# Script 2
lock = lockfile.FileLock("file.lock")
with lock:
    with open("samefile.txt", "a") as f:
        for line in range(10):
            f.write(f"Script 2: Line {line} \n")

```
Here, both scripts use the **lockfile** module to lock the file **file.lock** before writing to the file **samefile.txt**. The **with** statement is used to obtain the lock and automatically release it after the protected code has executed. This ensures that only one script can write to the file at a time and prevents the race condition.



“This article was created with the help of AI and Cover From Dall.e2”
Here's How To Learn Data Science For Free 💯 In 2023
Tags: beginners, database, sql, datascience
Published: 2023-02-17 17:53:59


## Introduction


- Data science is an important part of the modern technology landscape, and for developers, it presents a unique opportunity to work with large datasets in order to uncover valuable insights. 

- Data science involves collecting, analyzing, and interpreting data from various sources in order to reach meaningful conclusions that can be used by businesses or organizations. 

- It requires skills such as programming languages like [Python](https://youtu.be/2VRXU2H4q0c) and R knowledge of databases like [SQL](https://www.youtube.com/watch?v=00loCpVmozI) understanding of statistical methods such as regression analysis visualization [tools](https://youtu.be/BiXqzWFJuIA) like Tableau or Power BI.

- Machine learning algorithms for predictive analytics natural language processing (NLP). deep learning techniques using neural networks etc. 

- For developers interested in getting into data science, there are many resources available online that provide tutorials on the basics of the topics mentioned above. 

- Additionally there are also boot camps offered by companies which offer comprehensive training programs designed specifically for aspiring data scientists who want hands-on experience working with datasets while developing their skillset quickly over a short period of time. 

- This type of program provides real-world projects where they can apply their newly acquired knowledge while receiving feedback from experienced professionals within the industry which allows them to rapidly improve their abilities furthermore efficiently than self-study alone would allow them too.  

- Overall, Data Science is an exciting field full of potential opportunities not only due to its potential job prospects but also because it allows us to unlock new information about our world through careful examination & interpretation of complex sets of data. 

- For any developer looking to get involved in this area, taking advantage of all resources available will help ensure success journey towards becoming a successful professional scientist!




###### IBM Offers FREE 💯 Online Courses In Data Science 💡

🎥 {% youtube V3WowRUEokU%}


#### Bonus

###### SQL 🔥 Get Expertise in SQL with These Top Free Courses💯🏆

🎥 {% youtube 00loCpVmozI%}


### Connect with Me 😊

#### 🔗 Links

[![linkedin](https://img.shields.io/badge/linkedin-0A66C2?style=for-the-badge&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/mahmoud-el-kariouny-822719149/)

[![twitter](https://img.shields.io/badge/twitter-1DA1F2?style=for-the-badge&logo=twitter&logoColor=white)](https://twitter.com/Mahmoud42275)
SF Bad Date List
Tags: react, node, javascript, beginners
Published: 2023-02-17 17:51:27

[St. James Infirmary](https://stjamesinfirmary) is seeking contributors for the [Bad Date List Application](https://sfbaddatelist.stjamesinfirmary.org/).  This app consists of 2 main parts a [react frontend](https://github.com/dennison-williams-stjames/sji-bdl-client) and a [nodejs API](https://github.com/dennison-williams-stjames/sji-bdl-api).  The Bad Date List is a community-based violence intervention tool utilized by sex workers to share information regarding “bad dates.” A Bad Date may be any person who threatens, behaves violently towards, robs, extorts, or engages in any behavior that violates the agreed upon terms and boundaries of the exchange. This list may also be used to report bad encounters with law enforcement. The Bad Date List application is scheduled to be delivered initialy to the sex-work community of the San Francisco Bay Area, but can easily be extended to support other regions.  Currently the frontend is a web application, but a migration to [expo](https://expo.dev/) for a universal codebase supporting web, Android, and IOS is [in the works](https://github.com/dennison-williams-stjames/sji-bdl-client/issues/3).
Importance of Filelock and how to use that in Python
Tags: python, programming, filelock, codenewbie
Published: 2023-02-17 17:48:36

We need the **filelock** module in Python to prevent race conditions in concurrent and multi-process applications. Race conditions occur when multiple processes or threads access the same resource simultaneously and the outcome of the application depends on which process finishes first.

For example, consider a scenario where multiple processes write to the same file. If two processes try to write to the file simultaneously, the second process may overwrite the changes made by the first process, leading to data corruption and incorrect results.

#### To install filelock

```bash
pip install filelock
```

#### Simple Example of **filelock** module to lock a file in Python:

```python
import os
from filelock import Filelock

lock = FileLock("file.lock")

with lock:
    with open("file.txt", "a") as f:
        f.write(f"Line written by process { os.getpid()}\n")

```
Here, You can name your lockfile anything you want, in our case, it is **file.lock**. This file will temporally create while acquiring the lock and it will automatically deleted after releasing the lock.
we use the **FileLock** class from the **filelock** module to lock the file **file.lock**. The **with** statement is used to obtain the lock and automatically release it after the protected code has executed. This ensures that only one process can access the file at a time and prevents race conditions.

The `os.getpid()` function is used to obtain the process ID, which is written to the file along with the line of text. This allows us to see which process wrote each line to the file.


### Summary
The **filelock** module provides a simple and reliable way to lock files and prevent race conditions. By using a lock file, you can ensure that only one process can access a shared resource at a time, and prevent data corruption and other issues that can occur when multiple processes access the same resource simultaneously. The filelock module is a great tool for developing concurrent and multi-process applications in Python, and it provides a simple and reliable way to lock files and prevent race conditions.



“Recently I had to work with filelock but I take some help from AI to understand and Implement this in my project.”
Take Your Web Development Skills to Next with Web API's
Tags: webdev, javascript, beginners
Published: 2023-02-17 17:30:22

Web API's is one of the most kept open secret in Web development. You hardly see it in text or any forum post. If you have used document.querySelector() or document.getElementById to interact with HTML element, you have made use of Web API's. Web API's are used typically with  JavaScript but it can be used with any programming Language. There are many many Web APIs available and it can be daunting going through each one. From media streaming to HTML drag and drop, Web API's are available. One thing is sure, Web API's will take your web development skills to another level.


In this post and subsequent ones, I will demonstrate Web API's fuctionality. I will start with Web Share API for sharing text,links, files and  any content to any selected target.

**Prerequisite: HTML, Javascript**
**Objective: To famailarise readers with Web Share API**

The Web share API has two methods
    1. navigator.canShare() method to validate data is shareble.
    2. navigator.share() method invokes the native sharing mechanism of the underlying operating system.

I will use the HTML skeleton below to demonstrate Web share API are at work.

```
<html>
<head>
<title>Share page </title>
</head>
<body>
        <div class="share">

            <h1 class="groupH">SHARE DONATION LINK</h1>
            <p class="groupP">Share a link to family and friends to make DONATION to your alma mata</p>

            <button class="btn-secondary share-link" type="submit" onclick="shareLink()">SHARE DONATION LINK</button>
        </div>
 <script type="text/javascript">
        const shareData = {
            title: 'Donation',
            text: 'Donation for my Alma matter',
            url: 'http://localhost:3080/share'
        }
        const shareLink = async (event) => {
        
            try {
                await navigator.share(shareData)
                console.log('Donation shared successfully')
            } catch (err) {
                console.log(err)
            }
        }


    </script>
</body>
<html>
```
In the script tag, I created a javascript object shareData that has the web page I want to share. I called navigator.share() with the shareData as parameter inside shareLink function. ShareLink is triggered when the user clicks the Share Donation Button. This will trigger the operating system sharing mechanism. 

## Finally
As demonstrated above, Web API's makes  web development easy. In my next post, I will demonstrate how to use Web Share API to share files. 

**Like and comment**, if you find this post educative.
Unpredictable behaviour of state in React
Tags: react, javascript
Published: 2023-02-17 17:14:39

const [x, setX] = useState(0);

const clickHandler = () => {
    for (let i = 0; i < 100; i++) {
      setX((x) => x + 1);
    }
}

useEffect(() => {
   console.log(x);
}, [x]);

In the above code, when we call the clickHandler function on button click, the state is directly updated to 100.

The useEffect that displays the value of x on console gives the output as:

0
100

I was expecting the following output on console:
0
1
2
3
...
100
The Insights of Trending wpc2025 Live Dashboard and Login
Published: 2023-02-17 17:09:55

The [WPC 2025 live login](https://theskydaily.com/wpc-2025-live/) can be done simply via their website. All you have to do is input the username and password of your Sabong account. Once you get logged in to the dashboard, you will be able to view its user-friendly interface. You will also come across highlights of previously streamed or missed matches. You can access them with a lot of ease and the instructions are available right there on the website. The organic content of the website is its best and most unique feature.
Final Weekend of the Linode Hackathon on DEV!
Tags: meta, linodehackathon, linode, linux
Published: 2023-02-17 17:05:16

---
title: Final Weekend of the Linode Hackathon on DEV!     
published: true
description: It's the final weekend of the Linode Hackathon on DEV. Don't miss your chance to participate!
tags: meta, linodehackathon, linode, linux
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k2vjkrgw7po8xu9u3ve1.jpg
---

#### *The Linode Hackathon on DEV closes on February 20th @ 11:59 PM UTC. Don't miss your chance to build a new app and win prizes for it!* 

--- 

The Linode Hackathon on DEV closes next Monday!

If you haven't joined in yet, we encourage you to consider it — Linode's global data centers make it a great cloud hosting choice for users who want to run their own virtual web server hands-on.

By submitting a valid project, you stand to win one of four Grand Prize packages, which include... 
- $1,000 USD in cash
- $312 credit to [our shop](https://shop.forem.com)
- A DEV sticker pack
- A glorious "Grand Prize" digital profile badge! 

In addition, 10 runners-up will win... 
- $250 USD in cash
- $162 USD at [our shop](https://shop.forem.com)
- A DEV sticker pack
- An enviable "Runner Up" digital profile badge

Finally, ALL participants with a valid project will get a DEV sticker pack, and a digital participant profile badge.   


**[>> Click here to read the rules and join in](https://dev.to/devteam/announcing-the-linode-dev-hackathon-377p).**


If you'd like to tell us how your project is coming or meet the other participants, check out the Linode Hackathon [Community Discussion Thread](https://dev.to/devteam/community-discussion-thread-linode-dev-hackathon-59k1). 

If you need help with your project or have a question about the hackathon rules or Linode, pop into the [help thread](https://dev.to/devteam/linode-dev-hackathon-help-thread-1cmo). We'll be happy to assist you there!


Good luck to everyone who submits a project for this contest.  We hope to see an entry from you!    

---
_Click [here](https://dev.to/devteam/announcing-the-linode-dev-hackathon-377p) to find all the info you'll need to get started._ ❤️
create a windows form in c# without visual studio
Published: 2023-02-17 17:04:40

**step 1**
intall c# and the mono compiler

**step 2**
next we need to write the code. This will make a blank window appear:

```cs
using System;
using System.Drawing;
using System.Windows.Forms;
 
public class app : Form
{
    static public void Main ()
    {
        Application.Run (new app ());
    }
}
```

**step 3**
we can compile this with:
`mcs main.cs -r:System.Windows.Forms.dll -r:System.Drawing.dll`
or:
`csc main.cs -r:System.Windows.Forms.dll -r:System.Drawing.dll`

next run it with `mono main.exe`. Boom! We have a window!

**step 4**
enjoy and have a good day!
#Rust 🦀 – Serializing and Deserializing data structures to JSON with Serde
Tags: englishpost, datatype, json
Published: 2023-02-20 23:39:54

---
title: #Rust 🦀 – Serializing and Deserializing data structures to JSON with Serde
published: true
date: 2023-02-17 16:51:33 UTC
tags: EnglishPost,DataType,EnglishPost,JSON
canonical_url: 
---

Hi !

While I was creating a [sample on how to use OpenAI APIs in Rust](https://github.com/elbruno/RustOpenAIAPIs), I relized that I needed to serialize and deserialize some data in JSON format. Lucky me, Serde JSON works great !

### [Serde JSON](https://github.com/serde-rs/json)

Serde JSON is a library for serializing and deserializing Rust data structures efficiently and generically12. It provides ways to convert between different representations of JSON data, such as:

- As a strongly typed Rust data structure. When you expect all or most of your data to conform to a particular structure and want to get real work done without JSON’s loosey-goosey nature tripping you up3.
- As an untyped JSON value. When you want to work with data that does not have a predefined structure3.
- As a stream of JSON events. When you need to read or write large messages with minimal memory overhead3.

### [Tool to convert JSON to Rust Structs](https://transform.tools/json-to-rust-serde)

My next step was to analyze one of the json response samples from OpenAI APIs, and manually create the data struct. I’m lazy, so I search and find this amazing website: [https://transform.tools/json-to-rust-serde](https://transform.tools/json-to-rust-serde)

2 seconds later, I have my structs to work with OpenAI APIs !

![](https://brunocapuano.files.wordpress.com/2023/02/image-5.png?w=1024)

Next week I’ll share more details about the [repo with samples on how to use OpenAI APIs in Rust](https://github.com/elbruno/RustOpenAIAPIs).

Happy coding!

Greetings

El Bruno

More posts in my blog [ElBruno.com](https://www.elbruno.com).

* * *
ChatGPT is available on Play Store. Link in the description. Download now and enjoy the power of AI.
Tags: chatgpt, ai, gpt3
Published: 2023-02-17 16:49:53

Get organized and stay connected with the GPT mobile app! #GPTapp
Available on Play Store. Download now.
https://play.google.com/store/apps/details?id=com.winggs.gpt_ai_bot
Getter and Setter functions in Solidity
Tags: web3, ethereum, solidity, blockchain
Published: 2023-02-17 16:49:46

>In Solidity, getter and setter functions are used to read and write values from variables.

Getter and setter functions are used in Solidity to read and modify the values of variables stored in a smart contract. Getters are functions that return a value, while setters are functions that modify the value of a variable. Getters and setters must be declared with the correct visibility to work properly. 

Getter and setter functions should be used instead of public variables, as public variables can be difficult to control. This is because getters and setters allow for more control over how data is accessed and modified, making it easier to maintain security within the contract. Additionally, using getters and setters can help reduce gas costs by avoiding unnecessary code deployment. 

When creating getter and setter functions for mapped structs, it is necessary to write custom functions to access or modify indexed values. This is because there is no automatic way to create getter or setter functions for mapped structs in Solidity. However, there are well-solved storage patterns available that can help guide developers when writing their getter and setter functions for mapped structs.

In Solidity, getters and setters are declared using the keyword "contract". For example, to create a getter and setter for a score variable, one would declare it as follows: 
```
contract Score { 
    uint score = 5; 
    function getScore() public returns (uint) { 
        return score; 
    } 
    function setScore(uint new_score) public { 
        score = new_score; 
    } 
}
```
Getters and setters are important for keeping control over variables in smart contracts. Public variables should be avoided as they can be difficult to keep track of. By using getters and setters instead, one can ensure that only authorized users have access to certain data or functions within the contract.

You have to send a transaction if you want to write to or change a state variable. On the other hand, you don't have to pay anything to read state variables.

 A setter is a function in Solidity that changes the value of a variable (modifies the state of the contract). When you declare your function, you must tell it what parameters it will take.

In Solidity, a getter is a function that returns a value.

##Example:
```
 // SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract SimpleStorage {
    // State variable to store a number
    uint public num;

    // You need to send a transaction to write to a state variable.
    function set(uint num) public {
        num = num;
    }

    // You can read from a state variable without sending a transaction.
    function get() public view returns (uint) {
        return num;
    }
}
```
 For more content, follow me at - https://linktr.ee/shlokkumar2303
From Gears to Code: A Mechanical Engineer's Journey into the World of Software Development
Tags: beginners, programming, java, career
Published: 2023-02-17 16:27:53

**

## Introduction:
**

 The engineering field is vast and diverse, offering students and professionals many opportunities to explore. In today's world, many engineers find that the skills they learned in one engineering area can be applied to another. This is the story of one mechanical engineer who made a massive leap into software development. And I am proud that It was me.

**

## Body:
**

 I had always been mesmerized by how things functioned. As a child, I would take apart my toys to see how they were put together and try to assemble them again. As I grew, My curiosity shifted to how bikes and cars work and how a refrigerator could work. This inquisitiveness led me to study mechanical engineering in college, where I learned how to design and build machines that could solve complex problems and got to know how the machines work.

I took an Internship at a government corporation during graduation, where I worked on designing, optimizing assembly, and non-destructive testing. I loved the work, but a question haunted me while using software for design. How do these commands work? What goes behind this software that made my job easy digitally? I started exploring other engineering areas and discovered it was a building of coding. That was my first baby step toward coding.
At first, I found it challenging to transition from mechanical engineering to software development. But I learned the basics, picking my first programming language, Java. I heard that Java is the hardest to understand. I want to challenge myself with the hardest. Gradually I learned the basics from the [W3 schools](https://www.w3schools.com/) website.
Along with this, I learned scripting languages, built a website, and deployed it on [netlify](https://vijay-sherr-arts.netlify.app/). Though it was not a responsive website and not entirely written, I was happy with what I learned and implemented. My ability to think analytically and solve complex problems was also helpful in programming.

With this knowledge, I could clear the interview and get placed in a top MNC. There they gave me training in Core Java, Spring, Spring Boot, Microservices, and DBMS. It was hard at first. Despite the challenges, I was determined to transition to software development.

My experience in mechanical engineering gave me a unique perspective on problem-solving and helped me to think creatively about software design. I quickly became an invaluable member of the team and was able to solve real-time problems in my assigned projects.

**

## Conclusion: 
**

I deem that pursuing your passion is always possible. I took a chance and made the leap from mechanical engineering to software development, which paid off. I made myself open to new opportunities and the value of transferable skills. My ability to think critically, problem-solve, and visualize complex systems helped me progress in a field that initially seemed foreign. Not to boast about myself, but anyone can successfully transition to a new domain with hard work and dedication.