teleren/devto huggingface dataset:
How to extract a project from a git repository
Tags: git, programming, subtree
Published: 2021-11-03 11:14:47

---
title:  How to extract a project from a git repository
tags:   [git,programming,subtree]
canonical_url: https://lorenzo-arena.github.io/2021/10/25/git-subtree/
published: true
---

The story of how I came into the undocumented `git subtree` command to help bring back order to an unfortunate
repository.

## A little bit of background

It can happen to make wrong choices; in the programming field, in particular, what often happens is that the
consequences arrive suddenly and like an unstoppable escalation. But catastrophisms aside, we come to a need born a few
days ago: in one of the git repositories that I use, which had to act as a "warehouse" for some small utilities, the
situation has exploded. Managing 15 small projects in a single versioning solution is a real nightmare, so I decided to
try to solve the situation, possibly without simply creating new repositories to start from scratch with the commit
history copied into them.

After a little bit of digging, I found a tool which I didn't know anything about: **subtree**.

Subtree is a script created by extern contributors in the git community and it's bundled in the git installation from
version *1.7.11*, but never added to the official documentation (you can, however, read some informations
[here](https://github.com/git/git/blob/master/contrib/subtree/git-subtree.txt>)). It allows one to create
*subtrees*, which are branches that will join the ones already existent but in an independent manner, creating something
like a new repository in the repository.

Subtree also offers some commands which enables the execution of really interesting operations: one of them is
`split`, which will create a new branch that will contain the commit history of a subfolder in particular. That
seems exactly what we need!

Let's suppose that the starting repository has a folder structure like this:

```
   repository
   │   .git
   │   .gitignore
   │
   └───project1
   │   │   file1_1
   │   │   file1_2
   │
   └───project2
   │   │   file2_1
   │   │   file2_2
   │
   └───project3
   │   │   file3_1
   │   │   file3_2
   │
```

Now if we wanted to extract the *project1* folder we can go like this: first we must create a subtree which will contain
only the commits involving files inside *project1*

```bash
$ git subtree split --prefix=project1 -b split-branch-project1
```

Then, we can move into another folder and create the future repository

```bash
$ mkdir project1
$ cd project1
$ git init
```

Let's execute a pull from the old repository, referencing the newly created branch:

```bash
$ git pull ~/repository split-branch-project1
```

At this point *project1* will contain only the commit history involving that project; by repeating the process for each
project we can have cleaner repositories without losing the history.
Wednesday Links - Edition 2021-11-03
Tags: spring, kotlin, cloud, microservices
Published: 2021-11-03 10:55:54

What is @PropertySource in Spring Framework? (3 min)♨️
https://www.java67.com/2021/10/what-is-property-source-in-spring.html

A list of cache providers (7 min)🪶
https://blog.frankel.ch/choose-cache/2/

AWS Lambda with Kotlin and Spring Cloud Function (10 min)☁️
https://rieckpil.de/aws-lambda-with-kotlin-and-spring-cloud-function/

Announcing Kotlin support for protocol buffers (3 min)🧧
https://developers.googleblog.com/2021/11/announcing-kotlin-support-for-protocol.html

A Kotlin Time DSL for Java 8 Time (3 min)⏱️
https://jworks.io/a-kotlin-time-dsl-for-java-8-time/

Avoid leaking domain logic (2 min)🚰
https://www.mscharhag.com/architecture/leaking-domain-logic

Laws and Principles of Software Development (14 min)⚖️
https://reflectoring.io/laws-and-principles-of-software-development/

Hibernate Reactive: is it worth it? (8 min)🧊
https://in.relation.to/2021/10/27/hibernate-reactive-performance/
Back to the roots
Published: 2021-11-03 10:48:16

Hi, DEV community!

I started out my career as a System Analyst which had to gather requirements but also programming.

After many years working as an IT Consultant with main focus on BPM (Business Process Management) on the business perspective and Business Analysis, I decided to go back to development and writing code.

In the last three years was part of the IT-Architecture Team and my focus in the team was mostly about Processes, Technology and Platform and IT Landscape modeling. 

A month ago, I started a new job, now I am part of the development team for BPM Automation. 

We chose Camunda BPM for automating processes. We are also using Java, Spring Boot and Oracle.

I would like to share with you, how I will be handling to get used to code again in these first three months.

Photo by [Felix Mittermeier](https://www.pexels.com/@felixmittermeier) on Pexels
Day 47-49/100 Data Structures: Objects and Arrays
Tags: 100daysofcode, programming, challenge, motivation
Published: 2021-11-03 10:18:04

"On two occasions I have been asked, ‘Pray, Mr. Babbage, if you put into the machine wrong figures, will the right answers come out?’ [...] I am not able rightly to apprehend the kind of confusion of ideas that could provoke such a question."

–– Charles Babbage, Passages from the Life of a Philosopher (1864)

![data](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/va26xeh01pnxrnpo9ump.png)
Can you find the bug in this piece of code? - RegExp edition 🌍
Tags: typescript, javascript, bugs, regex
Published: 2021-11-03 10:01:30


Hey there! 👋

I'm back with another installment of **Find the bug**, this time with Typescript/Javascript. Regular expressions are useful, but can behave in some unexpected ways. Can you tell me what the code below will output and what the cause for it is? 

#### !! Don't look at the comments to prevent spoilers if you want to solve it by yourself !!

----

**Buggy code**
```ts
const TEST_REGEXP = /[a-z0-9]+_[a-z0-9]+/gi;

function isValidName(value) {
    if (typeof value !== 'string') return false;

    return TEST_REGEXP.test(value);
}

const filenames = [
  "test_1",
  "test_1",
  "test_2",
  "other_test",
  "some_file"
];

for (let name of filenames) {
    console.log(isValidName(name));
}
```

### Now then, can you find the bug?
Make Factory More Organized - laravel 
Tags: php, laravel, programming, beginners
Published: 2021-11-03 09:58:53

In Factory, it is possible to have in one table more than one set of fields, each sum expressing a specific category. It is better to put them in a different function for each of them :- 

```php
    public function doctor()
    {
        return $this->state(function (array $attributes) {
            $workDays = ['I, III, V', 'II, IV'];

            return [
                'role_id' => User::ROLE_DOCTOR,
                'doctor_licence_no' => $this->faker->bothify('???-######'),
                'doctor_licence_start_date' => $this->faker->dateTimeBetween('-15 years', '-3 years'),
                'doctor_licence_end_date' => $this->faker->boolean(35) ? $this->faker->dateTimeBetween('-3 years', '-10 days') : null,
                'doctor_stamp_number' => $this->faker->randomNumber(6),
                'doctor_hospital_name' => $this->faker->company(),
                'doctor_specialty' => $this->faker->jobTitle(),
                'doctor_department' => $this->faker->catchPhrase(),
                'doctor_biography' => $this->faker->text(1000),
                'doctor_work_days' => $workDays[mt_rand(0,count($workDays)-1)],
                'doctor_work_hours' => '9-5',
            ];
        });
    }

    public function patient()
    {
        return $this->state(function (array $attributes) {
            $genres = ['male', 'female'];

            return [
                'role_id' => User::ROLE_PATIENT,
                'patent_birth_date' => $this->faker->date(),
                'patient_declared_address' => $this->faker->address(),
                'patient_home_address' => $this->faker->address(),
                'patient_phone_no' => $this->faker->phoneNumber(),
                'patient_gender' => $genres[mt_rand(0,count($genres)-1)],
                'patient_personal_code' => $this->faker->randomNumber(9),
                'patient_social_number' => $this->faker->randomNumber(6).'-'.$this->faker->randomNumber(6),
                'patient_last_visit_time' => $this->faker->dateTime(),
                'patient_last_visit_reason' => $this->faker->words(rand(2,3), true),
                'patient_description' => $this->faker->text(1000),
            ];
        }); 
   }
```
Then in Seeder you call what you want to do :-
```php
User::factory(100)->doctor()->create();
User::factory(1000)->patient()->create();
```
Source:-

https://github.com/LaravelDaily/Laravel-Users-Admin-Doctor-Patient/blob/main/database/factories/UserFactory.php

https://github.com/LaravelDaily/Laravel-Users-Admin-Doctor-Patient/blob/main/database/seeders/UserSeeder.php

I hope someone can benefit from it.
Deploying to AWS EC2
Tags: javascript, aws
Published: 2021-11-03 09:44:53

My team was building a project where users can write posts and comments [(link)](http://ec2-3-36-50-211.ap-northeast-2.compute.amazonaws.com:3000/api/). This project is mostly comprised of CRUD operations and used MongoDB. This post will be going over how I deployed this project using AWS EC2.

My experience with deploying an app in the past was mostly just firebase. Google makes it pretty easy for users to deploy their apps but this time I tried to use AWS because I really wanted to know why it was so widely used. The process was actually very different from firebase. 

The first problem was that AWS provides so many services for deploying an app which makes it difficult to know which one is the right service for me. But in the end I chose EC2 because it's the service used by companies and I wanted to get some exposure to it. 

I think the biggest difference between deploying with EC2 and firebase was that AWS actually provided me with a server (online computer). You have to actually choose an operating system. I went with the Linux operating system provided by Amazon because it was free. I think Ubuntu is another popular option. This whole process is called creating an "instance".

While you are creating an instance, it depends on what you are doing but if you are deploying a mini app you just have to set the security settings so that the ports that you use are open.  Once you are done with that you are ready to launch your instance.

Your instance was launched, now you have to deploy your app on it. Because my app was built using Node.js I downloaded Node.js and git so that I can download my project using git commands. Once you download your app, you run it using "npm run start:prod" for Node apps. Then you are set to go! If you access the URL provided by AWS then you will see that your app is running live. But the problem is that once you shut your app down, the app stops running. To fix this problem you have to use a program that keeps it running at all times. There are multiple libraries that you can use to implement this such as "forever", "pm2", and etc. I used "pm2" because it was more widely used.
Free courses for november
Published: 2021-11-03 09:07:01

Some of my courses, free this month :)

**Ethical Hacking**
[Ethical Hacking: Introduction to Exploits](https://www.udemy.com/course/ethical-hacking-introduction-to-exploits/?couponCode=REDHEAD)
[Ethical Hacking: Hacking Web Apps](https://www.udemy.com/course/ethical-hacking-web-app-hacking/?couponCode=REDHEAD)
[Ethical Hacking: SQL Injection for Beginners](https://www.udemy.com/course/sql-injection-tutorial/?couponCode=REDHEAD)

**Cyber Security**
[Cyber Security: Secure Passwords](https://www.udemy.com/course/cyber-security-secure-passwords-on-linux/)
[Cyber Security: Linux AppArmor](https://www.udemy.com/course/apparmor-linux-security/?couponCode=REDHEAD)

**Programming**
[Make Simple Games with Python](https://www.udemy.com/course/make-simple-games-with-python/?couponCode=CD5055F2EAEC3DFE0215)
[awk tutorial](https://www.udemy.com/course/awk-tutorial/)
[Redis databases](https://www.udemy.com/course/redis-database-tutorial/)
An insight into how bot detection works
Published: 2021-11-03 08:59:13

Detecting a bot is not a piece of cake - knowing that a false positive can lead to unhappy human visitor, who may leave your website.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vgp53cs3eh5aluieanwc.png)

As you can see in attached diagrams, modern methods of Bot detection rely both on traces which can be found on site's access (HTTP/S) log file, and JavaScript-related features which can be checked only if client's browser does support JavaScript (lack of JavaScript is a strong indication that we're dealing with a bot).

JavaScript checks can go a long way, even detecting input / output devices and checking mouse / keyboard activity.

'Does IP belong to a Datacenter' - this check requires maintaining a database of such IPs - and usually obtained by external vendors.

If you're interested in using BotMeNot as a beta tester or want to find out more about this topic feel free to visit https://botmenot.com/
Back to Java
Tags: todayilearned, java, beginners
Published: 2021-11-03 08:50:54

I stopped learning and programming Java and JEE 12 years ago. Since then, too many things had happened in the field and today I am starting a collection of posts trying to refresh my knowledge about the technology that was revolutionary in the 90's and mainstream in the 00's.

So today, I will start with the basics.

# What is the current version of Java

According to [dev.java](https://dev.java/) latest version of Java is **17**. Wow! I was once certified in JSE 1.4 👴🏻 There is a good collection of articles [there](https://dev.java/learn/) about how to learn Java in that web page, that covers from the basics to the JVM. If I finally want to fully refresh my Java dev skills probably I would start there.

However, I was more interested in understanding the history and evolution of Java since version 1.4 to nowadays to catch up fast on the features that were added and how to leverage them. So the answer is in the [Wikipedia's article about version history](https://en.wikipedia.org/wiki/Java_version_history). If you are planning to recycle yourself, it is worth to spend some time to see the evolution and features that were added in every version. And probably you will need a bit more time to understand the impact of every feature.

I found the following as the most relevant features introduced during these years:

* J2SE 5.0: introduction of generics and metadata (aka annotations)
* Java SE 6: Support for pluggable annotations 
* Java SE 7: JVM support for dynamic languages
* Java SE 8: Language-level support for lambda expressions and default methods, Project Nashorn (which I know that is now depretated)
* Java SE 9: Modularization of the JDK under Project Jigsaw

In my light reading exercise I did not find any deep transformation in the language after Java SE 10, but I may be completely wrong.

BTW, Oracle is still the owner of the Java trademark.

# What about Java Enterprise Edition

This will be covered in a future blog entry, but let's anticipate a few spoilers:

* Java Platform, Enterprise Edition (Java EE) was maintained by Oracle until [version 8](https://www.oracle.com/java/technologies/java-ee-glance.html)
* On September 12, 2017, Oracle Corporation announced that it would submit Java EE to the Eclipse Foundation. Oracle owns the trademark for the name "Java" and renamed the Java EE platform to [Jakarta EE](https://jakarta.ee/). Latest version of Jakarta EE is 9.1 (May 25 2021), with JDK 11 support
* In parallel, [Microprofile](https://microprofile.io/) project was created as an open forum to optimize Enterprise Java for a microservices architecture by innovating across multiple implementations and collaborating on common areas of interest with a goal of standardization.

What do you think? Any important topic I am missing? I appreciate your feedback
HacktoberFest 2021: Lessons to learn.
Published: 2021-11-03 05:58:00

Imagine refreshing page on getting the email of 4th pull request being merged; just to see that the repository you were contributing to, has be excluded. 
I was contributing with all my heart to that one but since it included DSA, it was not eligible for the fest. A teeny tiny part of it hurts, but I was glad I joined it. I learnt about git, GitHub, open source, how it works(I even made YouTube videos for that repo).
My instant reaction to this was a hunt for other repositories I could contribute to (Won't say it was easy).
I even learnt new things like canvas and ascii art.
It was easy, all it requires is a hunger to complete and a will to learn.
Failing and falling are the inevitable part of the process, what matters is repair and running after that.
It is easy to lose trust in yourself, but when you've worked so hard, you know you wouldn't settle.
My 4th pr matured on 1st of Nov and I have successfully made 5 of them.
In the end it's not about winning or losing. But hoping and learning. :)
code every day with me
Tags: javascript, programming, 100daysofcode, algorithms
Published: 2021-11-03 08:01:22

##--DAY 14--
Hi, I am going to make #100DaysOfCode Challenge. Everyday I will try solve 1 problem from leetcode or hackerrank. Hope you can go with me until end.
**Now let's solve problem today:**
- Problem: Pascal's Triangle
- Detail: [here](https://leetcode.com/problems/pascals-triangle/)
- My solution (javascript): 
```
var generate = function(n) {
    if(n==1) return [[1]];
    if(n==2) return [[1],[1,1]];
    let arr=[[1],[1,1]];
    for(let i=2;i<n;i++){
        arr[i]=[1];
        for(let j=1;j<i;j++){
            arr[i].push(arr[i-1][j-1]+arr[i-1][j]);
        }
        arr[i].push(1);
    }
    return arr;
};
```
Improving your reasoning with Arrays in java
Published: 2021-11-03 07:21:05

<b>QUESTION:</b>
<b>Write a function that takes an array of integers as an argument and returns a value based on the sums of the even and odd numbers in the array. Let X = the sum of the odd numbers in the array and let Y = the sum of the even numbers. The function should return X-Y</b>
<b>The signature of the function is</b>: int f(int [] a)


Examples
<table>
<thead>
  <tr>
    <th>if input array is</th>
    <th>return</th>
  </tr>
</thead>
  <tr>
    <td>{1}</td>
    <td>1</td>
  </tr>
  <tr>
    <td>{1, 2}</td>
    <td>-1</td>
  </tr>
 <tr>
    <td>{1, 2, 3}</td>
    <td>2</td>
  </tr>
 <tr>
    <td>{1, 2, 3, 4}</td>
    <td>-2</td>
  </tr>
 <tr>
    <td>{3, 3, 4, 4}</td>
    <td>-2</td>
  </tr>
<tr>
    <td>{3, 2, 3, 4}</td>
    <td>0</td>
  </tr>
<tr>
    <td>{4, 1, 2, 3}</td>
    <td>-2</td>
  </tr>
<tr>
    <td>{1, 1}</td>
    <td>2</td>
  </tr>
<tr>
    <td>{}</td>
    <td>0</td>
  </tr>
</table>

<b>ANSWER:</b>
```java

import java.util.*;
public class ArraySum {
	
	public int f(int[] a) {
		int X = 0;  // initialization for sum of odd numbers in an array
		int Y = 0; // initialization for sum of even numbers in an array
		for(int i = 0; i<a.length; i++) {
			if(a[i] % 2 == 1) {
				X+=a[i];
			}
			if(a[i] % 2 == 0) {
				Y+=a[i];
			}	
	    }
		return X-Y;
		 
	}

	public static void main(String[] args) {
	
		ArraySum obj = new ArraySum();
		int [] A = {1};
		int [] B = {1, 2};
		int [] C = {1, 2, 3};
		int [] D = {1, 2, 3, 4};
		int [] E = {3, 3, 4, 4};
		int [] F = {3, 2, 3, 4};
		int [] G = {4, 1, 2, 3};
		int [] H = {1, 1};
		int [] I = {};
		
		// Printing results on the screen
		System.out.println("Result for array A "+Arrays.toString(A)+" is "+obj.f(A));
		System.out.println("Result for array B "+Arrays.toString(B)+" is "+obj.f(B));
		System.out.println("Result for array C "+Arrays.toString(C)+" is "+obj.f(C));
		System.out.println("Result for array D "+Arrays.toString(D)+" is "+obj.f(D));
		System.out.println("Result for array E "+Arrays.toString(E)+" is "+obj.f(E));
		System.out.println("Result for array F "+Arrays.toString(F)+" is "+obj.f(F));
		System.out.println("Result for array G "+Arrays.toString(G)+" is "+obj.f(G));
		System.out.println("Result for array H "+Arrays.toString(H)+" is "+obj.f(H));
		System.out.println("Result for array I "+Arrays.toString(I)+" is "+obj.f(I));

	}

}

```
<b>OUTPUT:</b>
```
Result for array A [1] is 1
Result for array B [1, 2] is -1
Result for array C [1, 2, 3] is 2
Result for array D [1, 2, 3, 4] is -2
Result for array E [3, 3, 4, 4] is -2
Result for array F [3, 2, 3, 4] is 0
Result for array G [4, 1, 2, 3] is -2
Result for array H [1, 1] is 2
Result for array I [] is 0

```
That's one of examples in java arrays that can improve your reasoning, practice as many challenges as you can to better your programming skills. Thank you for taking time to read through this post.
Using Firebase Admin with Next.js
Tags: firebase, nextjs, javascript, serverless
Published: 2021-11-03 07:17:42

## Initialize Next.js Starter
```bash
npx create-next-app project-name
```

## Install firebase-admin
```bash
npm install firebase-admin
```

## Generate the firebase config
```js
// File: lib/fireConfig.js

export const fireConfig= {
// Place the json obtained as in
// https://firebase.google.com/docs/admin/setup#initialize-sdk
}
```

## Create firebase.js
```js
// File: lib/firebase.js

import admin from 'firebase-admin'
import { fireConfig } from './fireConfig'

try {
  admin.initializeApp({
    credential: admin.credential.cert(fireConfig),
  })
  console.log('Initialized.')
} catch (error) {
  /*
   * We skip the "already exists" message which is
   * not an actual error when we're hot-reloading.
   */
  if (!/already exists/u.test(error.message)) {
    console.error('Firebase admin initialization error', error.stack)
  }
}

export default admin
```
## Use firebase-admin in Next.js API Routes
```js
// File: pages/api/tryFirebaseAdmin.js

import admin from '@/lib/firebase'

export default async function handler(req, res) {
    const firebase = admin.firestore()

    // Return promise to handle serverless function timeouts
    return new Promise((resolve, reject) => {
       firebase
        . // set of operations
        .then(() => {
          res.status(200).json({ data })
          res.end()
          resolve()
        })
        .catch((e) => {
          res.status(405).json(e)
          res.end()
          resolve()
        })
    }

}
```

## Example
This page itself obtains data from server side data fetch with firebase-admin and Next.js. Feel free to add any problems in comments, or email me at [rishi18304@iiitd.ac.in](mailto:rishi18304@iiitd.ac.in). Find my portfolio's code at [rishi-raj-jain/rishi.app](https://github.com/rishi-raj-jain/rishi.app)