teleren/devto huggingface dataset:
Maximizing Score with Tokens - 948 - Bag of Tokens in Go
Tags: go, leetcode, learning, beginners
Published: 2024-03-04 06:38:52

## Introduction
Welcome to the second post of my "Journey into GoLang" series! In this series, I'll document my GoLang programming exploration by solving LeetCode problems. Today, we are solving the **948 - Bag of Tokens** problem.

## The Problem Description:

You start with an initial power of power, an initial score of 0, and a bag of tokens given as an integer array tokens, where each tokens[i] donates the value of tokeni.

Your goal is to maximize the total score by strategically playing these tokens. In one move, you can play an unplayed token in one of the two ways (but not both for the same token):

Face-up: If your current power is at least tokens[i], you may play token, losing tokens[i] power and gaining 1 score.
Face-down: If your current score is at least 1, you may play token, gaining tokens[i] power and losing 1 score.

Return the maximum possible score you can achieve after playing any number of tokens.

Example:
Let's consider an example to understand the problem better:
Input:
tokens = [200, 100]
power = 150
Output:
1

[LeetCode Link](https://leetcode.com/problems/bag-of-tokens/description)

## Approach:
To solve this problem efficiently. We'll sort the tokens array to prioritize playing tokens with lower values first. Then, we'll iterate through the tokens array, playing tokens face-up if possible, and face-down if necessary. We'll keep track of the maximum score achieved throughout the process.

```go
import (
	"fmt"
	"sort"
)

func bagOfTokensScore(tokens []int, power int) int {
	sort.Ints(tokens)
	left, right, score := 0, len(tokens)-1, 0
	maxScore := 0
	for left <= right {
		if power >= tokens[left] {
			power -= tokens[left]
			left++
			score++
			if score > maxScore {
				maxScore = score
			}
		} else if score > 0 {
			power += tokens[right]
			right--
			score--
		} else {
			break
		}
	}

	return maxScore
}

func main() {
	fmt.Println(bagOfTokensScore([]int{200, 100}, 150)) // Output: 1
}
```

[Github Code](https://github.com/shareef99/go-leetcode-problems/blob/main/problems/948-bag-of-tokens/main.go)

Thank you for joining me on this journey, and I look forward to sharing more discoveries with you in the upcoming posts!

Social Links
- Twitter: [@shareef99\_](https://twitter.com/shareef99_)
- LinkedIn: [Nadeem Shareef](https://www.linkedin.com/in/nadeem-shareef/)
- Github: [shareef99](https://github.com/shareef99)
Taking over maintenance of Perl distribution Date::Holidays::ES and releasing version 0.03
Tags: perl, opensource, release
Published: 2024-03-04 06:38:08

---
title: Taking over maintenance of Perl distribution Date::Holidays::ES and releasing version 0.03
published: true
description: Release of the Perl distribution Date::Holidays::ES for national holidays of Spain
tags: perl, opensource, release
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
# published_at: 2024-03-03 14:00 +0000
---
Back in June of 2020 I created a PR for the repository for the Perl distribution [Date-Holidays-ES](https://metacpan.org/pod/Date::Holidays::ES).

The [PR](https://github.com/fmerges/Date-Holidays-ES/pull/1) was a basic thing of updating the build system, since the distribution was using the embedded [Module::Install](https://metacpan.org/dist/Module-Install/view/lib/Module/Install.pod).

Actually I had created the repository based on a so-called [Gitpan](https://github.com/evalEmpire/gitpan) repository. The Gitpan repositories are a huge collection of repositories (35.000+) of CPAN (BackPAN) distributions (the Perl package manager, Comprehensive Perl Archive Network). 

Since [Date-Holidays-ES](https://metacpan.org/pod/Date::Holidays::ES) did not have a Git repository at the time, I had created a fork from Gitpan and written up my patch from a fork of the fork and created a PR.

I sent the whole recipe to the author of [Date-Holidays-ES](https://metacpan.org/pod/Date::Holidays::ES) [Florian Merges](https://github.com/fmerges), who responded positively.

I hade since then created an additional an additional [PR](https://github.com/fmerges/Date-Holidays-ES/pull/2) and things where slowly progressing.

My third [PR](https://github.com/fmerges/Date-Holidays-ES/pull/3) stranded, but I did not think much of it until February of 2022 and when Florian wrote me and informed me that he did not have the time to take care of the distribution and he provided me `COMAINT` on CPAN and I got permissions to upload new distributions.

This dialogue was saved in my backlog of things to follow up on and finally this weekend I found the time to have a look at it.

I set up a fork of [Florian's repository](https://github.com/fmerges/Date-Holidays-ES), reapplied the patch and migrated the build system from [Module::Install](https://metacpan.org/dist/Module-Install/view/lib/Module/Install.pod) to [Dist::Zilla](https://metacpan.org/pod/Dist::Zilla) to make it easier for me to maintain the distribution.

Finally I uploaded version 0.03, which is now available on CPAN if you are interested in programmatically work with national Spanish holidays or want to do something via the APIs offered by [Date::Holidays](https://metacpan.org/pod/Date::Holidays), which is a wrapper around the distributions in the Date::Holidays::* namespace, which is actually what I am maintaining and the reason why I keep an eye on the varies distributions related to this work.

I am very much a TODO list person and most often I will eventually come to the task needed to be done, apparently this might take years, but little by little we progress.
Java 구조, 2024-03-04
Tags: java
Published: 2024-03-04 06:33:26

모델1 구조
: 뷰와 로직을 모두 JSP 페이지 하나에서 처리하는 구조를 말합니다
JSP와 자바빈 혹은 서비스 클래스로 구성되어 있습니다.
JSP 페이지 내에 로직 처리를 위한 자바 코드가 출력을 위한 코드와 함께 섞여있습니다. 브러우저에서 요청이 들어오면 JSP 페이지는 자신이 직접 자바빈이나 따로 작성한 서비스 클래스를 이용하여 작업을 처리하고, 그 처리한 정보가 전달되어 브라우저에 나타납니다.

구조가 단순하여 익히기 쉽고, 숙련된 개발자가 아니더라도 구현이 용이합니다.

출력을 위한 뷰 코드와 로직 처리를 위한 자바 코드가 혼재되어 있기 때문에 JSP 코드 자체가 복잡해집니다. 또한 JSP 코드에서 백엔드와 프론트엔드가 함께 있기 때문에 분업에 용이하지 않습니다. 유지보수가 어렵습니다.

모델2 구조
: JSP페이지와 서블릿, 로직을 위한 클래스가 나뉘어 브러우저 요청을 처리합니다.
서블릿, JSP, 자바빈 혹은 서비스 클래스로 구성되어 있습니다.
요청이 들어오면 요청에 대한 로직 처리는 이를 처리할 Model인 서비스 클래스 혹은 자바빈이 담당하고, 요청 결과는 유저에 결과를 보여줄 View인 JSP에 출력되며, 이를 위한 흐름 제어는 Controller인 서블릿이 담당합니다.

출력을 위한 뷰 코드와 로직 처리를 위한 자바 코드를 분리했기 때문에 JSP 모델 1에 비해 코드가 복잡하지 않습니다.
View, 로직처리에 대한 분업이 용이하며, 유지보수가 용이합니다.

구조가 복잡하여 습득이 어렵고 작업량이 많습니다. Java에 대한 깊은 이해가 필요합니다

_참조 : https://hsp1116.tistory.com/9_
How to get refresh token in Vite Vue 3
Tags: vue, node
Published: 2024-03-04 06:26:00

```
<script setup>

const accessrefresh = async () => {
	axios.defaults.headers.common['Authorization'] = storeaccesstoken.accesstoken;
	await axios.create({withCredentials: true}).post("http://localhost:81/auth/refresh/")
        .then((response) => {	axios.defaults.headers.common['Authorization'] = response.data.token;
			storeaccesstoken.stateAccessToken(response.data.token);
		})
		.catch((errors) => {
			console.log("errors access refresh: ",errors);
			if(errors?.response?.data?.message==='error') {
				Swal.fire({
                title: "Error!",
                text: "Access denied!",
                icon: "error",
                confirmButtonText: "Log in please!"
              });
			}
			storeaccesstoken.stateAccessToken(null);
			storeaccesstoken.setStateUserFalse();
		  	router.push({ path: '/login' })
		});
};

onBeforeMount(() => {
	window.addEventListener("beforeunload",accessrefresh());
})

<script>
```
Quantum Code Review - (March Update 2024) Shocking Facts About This Must Know!
Published: 2024-03-04 06:19:29

If you still don't understand what's going on here, I'll make this quite manageable. I, in part, stand together with this weak view. Pros often suppose that it's OK to ignore it. In many aspects this innovation is more universally accepted than this motion. Don't become enthralled with the notion of having this like this. It is a shock to the system how insiders can deal with an obvious assignment like this. Way to go, nuts. There's no sign of that yet. 

I agree with the admonition expressed by some to seek out the occasional this. Some game plan is still in the early stages. If you do this, you'll cover yourself well. I ought to get exclusive rights to that trait. Nevertheless, there isn't a reason for it. I've been using this whatchamacallit over the last week and have found it to be really nice. 

I am not here to defend this factor that way. How does she do it? I'm a bit of a workaholic. There is a community discussing a strategy. Otherwise, things are OK now for a gimmick. You might want to get a membership in Quantum Code of the Month Club. As usual, you probably won't get a Quantum Code that dispatches a feeling for a Quantum Code. That doubt was designed by them. Is this a decent option? 

Click Here =>> https://www.outlookindia.com/business-spotlight/quantum-code-review-2023-trading-robot-worth-investing-with-what-customers-have-to-say--news-296779 


https://gamma.app/public/Quantum-Code-Review-wgjtk8fke8wqedg 
https://t.ly/quantumcode 
https://s.id/quantumcode 
https://n9.cl/quantumcodereview 
https://bit.ly/quantumcodereview 
https://tinyurl.com/quantumcodeprice 


https://medium.com/@frecogune/quantum-code-2024-is-it-legit-or-a-scam-23e7ba3f7508 
https://www.eventogo.com/event/quantum-code-review-honest-user-ratings-explained-by-crypto-traders-2024/ 
https://quantum-code.webflow.io/ 
https://schnink-sqiack-sreud.yolasite.com/ 
https://www.scoop.it/topic/quantum-code-by-frecogune-lee 
https://paidforarticles.com/what-is-quantum-code-review-explained-by-crypto-traders-2024-779332 
https://www.deccanherald.com/brandspot/sponsored/quantum-ai-is-auto-trading-software-really-making-money-in-2023-beware-of-fake-reviews-1232577.html 
https://www.mid-day.com/lifestyle/infotainment/article/quantum-gpt-trading-bot-legit-or-scam-is-quantumgpt-really-work-how-to-use--23315670
How To Make Your Own Google Translator App With Python Tkinter & Googletrans
Tags: webdev, beginners, programming, python
Published: 2024-03-04 06:07:27

Have you ever wondered why we rely on translators? Hiring a human translator who can be available 24/7 for all our translation needs seems like a distant dream. That's where Google comes in

#googletranslate #linkedin #coding #pythonprogramming #python3 #webdevelopment #frontend #backenddeveloper #linkedincommunity #python 



Learn How To Make Your Own Google Translator App With Python Tkinter & Googletrans

🤩🥳



https://codemagnet.in/2024/03/04/how-to-make-your-own-google-translator-app-with-python-tkinter-googletrans/
Spring Boot 암호화, 2024-03-04
Tags: springboot
Published: 2024-03-04 06:00:09

configuration.EncryptionConfig.java
```
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class EncryptionConfig {
    @Bean
    public PasswordEncoder encoder(){
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

}
```

비밀번호를 암호화하기 위해서 PasswordEncoderFactories를 사용

service.ApiServiceImpl.java
```
boolean checkPassword = encryptionConfig.encoder().matches(loginDTO.getPassword(),member.getPassword());
```
비밀번호를 일치하는지 여부를 확인하기 위해서 matches 메소드 사용
비밀번호 외 암호화가 필요한 개인정보, 주민등록번호와 같은 것은 복호화가 필요하므로

provider.EncoderProvider.java
```
@RequiredArgsConstructor
@Component
public class EncoderProvider {

    public String encrypt(String regNo) {
        byte[] regNoBytes = regNo.getBytes();
        byte[] encodeByte = Base64.encodeBase64(regNoBytes);

        return new String(encodeByte);
    }
    public String decrypt(String regNo) {
        byte[] regNoBytes = regNo.getBytes();
        byte[] decodeByte = Base64.decodeBase64(regNoBytes);

        return new String(decodeByte);
    }

}
```
Base64로 인코더 후 Base64를 디코딩
How to Deploy a RESTful API with .NET Core to Azure App Service Using Azure SQL and Entity Framework
Tags: restapi, azure, api, azureappservice
Published: 2024-03-04 05:43:54

Hey **Dev.to community!**

I'm excited to share with you all a comprehensive guide that walks through the process of building and deploying a RESTful API using .NET Core, integrated with Azure SQL via Entity Framework, and then deploying it to Azure App Service — all within Visual Studio.

**What You'll Learn**:

Creating a RESTful API with .NET Core, detailed from scratch.
Integrating Azure SQL Database using Entity Framework for smooth and efficient data management.
Effortless Deployment from Visual Studio to Azure App Service, making your API live and accessible to the world.
Testing Your API both locally using Swagger UI and in the cloud post-deployment.
This tutorial is aimed at developers of all levels who are interested in stepping into the world of cloud services with Azure, or those looking to consolidate their knowledge by applying it to a practical project.

**Why This Matters**:

Deploying applications to the cloud is a critical skill for modern developers. This guide aims not only to teach you how to deploy an application but also to give you a clear understanding of working with Azure services and .NET Core.

Check out the full video tutorial here: {% embed https://youtu.be/AHEbBaGG_RA %}

I'm looking forward to your feedback, questions, or insights in the comments below! Let's make the cloud our playground. 🚀

#NETCore #Azure #RESTfulAPI #CloudComputing #DeveloperTutorial
Top 5 JavaScript Frameworks for Frontend in 2024
Tags: webdev, javascript, programming, react
Published: 2024-03-04 05:35:15

1. [React](https://github.com/facebook/react)
2. [Refine](https://github.com/refinedev/refine)
3. [Angular](https://github.com/angular/angular)
4. [Svelte](https://github.com/sveltejs/svelte)
5. [Vue](https://github.com/vuejs/vue)

_**Vote your favourite one in comment section✍️**_

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r04e555nvyv7yeo71cj2.png)
Catch me on : [GitHub](https://github.com/deepakydv9315) || [Codepen](https://codepen.io/deepakydv9315) || [Instagram](https://www.instagram.com/syco_coders/)
Differences between forEach and map in JavaScript
Tags: webdev, javascript, beginners, programming
Published: 2024-03-04 05:30:55

The primary differences between `forEach` and `map` in JavaScript (often used with arrays) lie in their return values and purposes:

**`forEach`**

- **Purpose:** Iterates over each element in an array, allowing you to perform an action on each element.
- **Return value:** `undefined`.
- **Use cases:**
    - Modifying elements in-place (be cautious of potential side effects).
    - Performing side effects like logging or DOM manipulation for each element.

**Example:**

```javascript
const numbers = [1, 2, 3];
numbers.forEach(number => console.log(number * 2)); // Output: 2, 4, 6 (no new array)
```

**`map`**

- **Purpose:** Creates a new array with the results of applying a callback function to each element in the original array.
- **Return value:** A new array containing the transformed elements.
- **Use cases:**
    - Transforming elements (e.g., doubling values, converting to uppercase).
    - Creating a new array based on a calculation or manipulation of the original elements.

**Example:**

```javascript
const numbers = [1, 2, 3];
const doubledNumbers = numbers.map(number => number * 2);
console.log(doubledNumbers); // Output: [2, 4, 6] (new array)
```

**Key Differences:**

| Feature        | `forEach`                                               | `map`                                                  |
|----------------|--------------------------------------------------------|----------------------------------------------------------|
| Return Value   | `undefined` (doesn't create a new array)              | A new array containing transformed elements                |
| Purpose        | Iterates and performs actions on existing elements    | Transforms elements and creates a new array               |
| Side Effects   | Can be used for in-place modifications (potentially risky) | Usually doesn't have side effects (creates a new array)     |
| Common Use Cases | Modifying elements, side effects (logging, DOM)       | Transforming elements, creating a new array based on logic |

**Choosing the Right Method:**

- Use `forEach` if you want to iterate through elements and perform side effects without creating a new array.
- Use `map` if you want to create a new array with transformed elements based on a callback function.
Angular Migration Query
Tags: angular, angular17, angularupdate, frontend
Published: 2024-03-04 05:22:49

Hello,
I've successfully transitioned an Angular application from version 11 to version 17. The initial build was constructed using webpack v4, but I've recently updated it to webpack v5. However, I'm encountering several challenges during the build and execution of the application, such as certain missing CSS files in the browser. I'm curious whether webpack v5 is compatible with Angular 17. For your convenience, I've attached a snippet from my package.json file.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ywoncogt0jrwmh6afr0p.png)
купить диплом
Published: 2024-03-04 05:17:11

[http://arena-diploma24.com](http://arena-diploma24.com)



Имея диплом, вы получаете ключ к успеху и лучшим рабочим местам. Если у вас нет возможности учиться, обратитесь к нам и купите диплом! Наша компания предлагает услуги по изготовлению подлинных образовательных документов на заказ. Мы гарантируем высокое качество и детализацию, а также признание наших документов учебными и государственными учреждениями. Не упустите возможность улучшить свою будущую карьеру, свяжитесь с нами и купите диплом уже сегодня!
Bay789 - Bay789.com.co - Giải Trí - Đặt Cược - Thể Thao - Live Casino
Published: 2024-03-04 05:09:37

BAY789 đã hoạt động kinh doanh trong thị trường giải trí và cá cược online hơn 15 năm rồi đến hiện tại có rất nhiều người chơi tham gia trải nghiệm tại nơi đây. Đông đảo người chơi tham gia vào giải trí chơi game vui vẻ và cũng có nhiều người tham gia cá cược tại nơi đây với những trò cá cược có tỉ lệ trả thưởng hấp dẫn không làm anh em thất vọng, khi vào trang game của nhà cái BAY789 chúng tôi bạn sẽ choáng ngợp bởi thiết kế giao diện đẹp mắt cuốn hút và tại nơi đây có rất nhiều trò chơi cho mọi người lựa chọn vào chơi. Khi có thời gian rảnh rỗi các bạn có thể vào chơi game giải trí nếu các bạn muốn đặt cược để kiếm thêm một ít tiền chi tiêu thì cũng có các tựa game để anh em đặt cược luôn. Chính vì thế hãy nhanh tay tìm hiểu và đăng ký mở tài khoản để vào trải nghiệm nhé các bạn tôi tin rằng nhà cái trang game BAY789 này sẽ không làm các bạn thất vọng, rất nhiều người đã tham gia rồi thì bạn còn chần chờ gì nữa.
Địa chỉ: 100C Đ. Hồng Hà, Phường 2, Tân Bình, Thành phố Hồ Chí Minh, Việt Nam
Postcode:  72108
SDT: 0967 118 6379
Email: bay789comco@gmail.com
Website: https://bay789.com.co/
TAGS: #BAY789comco #taiBAY789 #linkBAY789 #nhacaiBAY789 #appBAY789 #BAY789comcodangky
 
Social Links:

https://www.facebook.com/bay789comco/

https://twitter.com/bay789comco

https://www.pinterest.com/bay789comco/

https://500px.com/p/bay789comco?view=photos

https://www.flickr.com/people/bay789comco/

https://www.youtube.com/@bay789comco

https://www.reddit.com/user/bay789comco/

https://www.blogger.com/profile/09671734826790206140

https://bay789comco.blogspot.com/

https://www.tumblr.com/blog/bay789comco
1 BHK Service Apartments in Gurgaon
Tags: servivedapartment, primelocation
Published: 2024-03-04 05:01:23

Discover comfort and convenience at **[Lime Tree 1BHK Service Apartments in Gurgaon](https://www.limetreehotels.com/1bhk-service-apartment-medanta-hospital-gurgaon/)**, ideally located near Medanta Hospital. Our thoughtfully designed apartments offer a perfect blend of elegance and functionality, providing a home away from home experience.

Enjoy the proximity to Medanta Hospital, ensuring easy access for those seeking accommodation close to medical facilities. Lime Tree 1BHK Service Apartments are equipped with modern amenities, ensuring a comfortable and hassle-free stay.
Ngx-ui-switch issue with angular version 16
Published: 2024-03-04 04:57:19

Hello, 
I am upgrading angular version 11 to 16 in this case when updated in angular 16 then getting following error - 
/src/assets/scss/app.scss?ngGlobalStyle - Error: Module build failed (from ./node_modules/mini-css-extract-plugin/dist/loader.js):
HookWebpackError: Module build failed (from ./node_modules/@angular-devkit/build-angular/node_modules/sass-loader/dist/cjs.js):
SassError: Can't find stylesheet to import.
5 │ @import '~ngx-ui-switch/ui-switch.component.scss';
  │         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  ╵
  src\assets\scss\custom\plugins\_switch.scss 5:9  @import
  src\assets\scss\app.scss 51:9                    root stylesheet

so how to fix this error. please help !
Thanks in advance !
How Many Weeks for Awareness Campaign Ads on Meta and Google 2024
Tags: webdev, javascript, programming, devops
Published: 2024-03-04 04:54:10


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f7xofl36unkac2ghbgz2.jpg)
The article discusses the process of determining the optimal duration for [awareness campaign](https://onlineearningtricks.com/how-many-weeks-for-awareness-campaign-ads-on-meta-and-google-2024/) ads on platforms like Meta and Google. It highlights the importance of understanding the dynamics of advertising on these platforms, as well as the power of awareness campaigns. The article also discusses the importance of understanding campaign objectives, target audience, and budget constraints when making this decision.

To create a strategic timeline, the author suggests conducting thorough research on audience behavior patterns, peak engagement times, and industry benchmarks. They also suggest leveraging platform insights to optimize targeting parameters, ad creative, and bidding strategies. The article also emphasizes the importance of striking a balance between frequency and reach in [awareness campaigns](https://onlineearningtricks.com/how-many-weeks-for-awareness-campaign-ads-on-meta-and-google-2024/). Excessive frequency can enhance brand exposure, while limiting it may restrict reach and fail to leave a lasting impression.

The article concludes by urging users to continuously monitor their awareness campaign performance metrics, including impressions, clicks, and engagement rates, across Meta and Google platforms. This continuous optimization is crucial for campaign success in the digital age. The article concludes by emphasizing the need for experimentation, adaptability, and data-driven decision-making to find the perfect duration for awareness campaign ads on Meta and Google.
**[Read More](https://onlineearningtricks.com/how-many-weeks-for-awareness-campaign-ads-on-meta-and-google-2024/)**

Also Read Our Blog:
**(1)**[Exploring Successful Product Innovation Examples 2024](https://onlineearningtricks.com/successful-product-innovation-examples/)
**(2)**[Product Listing Ads Your Ultimate Guide to Effective E-Commerce Promotion 2024](https://onlineearningtricks.com/product-listing-ads-your-ultimate-guide/)
for more information please visit the website:**[onlineearningtricks.com](https://onlineearningtricks.com/)**