”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 使用 OpenAI GPT 和 DALL·E 模型,使用 AI/ML API、Next.js、React 和 Tailwind CSS 构建 AI 贴纸制作平台。

使用 OpenAI GPT 和 DALL·E 模型,使用 AI/ML API、Next.js、React 和 Tailwind CSS 构建 AI 贴纸制作平台。

发布于2024-11-01
浏览:393

I got bored. You too? ?

Hmm... ?

What about creating an AI Sticker Maker platform? To be honest, it's a really interesting idea. And hey, we might even generate some profit by simply integrating Stripe as a payment provider. ? Yeah, why not?

So, let's get started. Or at least give it a shot! ?

Quick Introduction ?

First things first, let's sketch out some pseudocode or make a plan (unless you're a true builder who codes from the hip). It should go something like this:

  1. User enters a prompt (a text description of how the sticker should look).
  2. Our AI Sticker Maker will generate a really cutesy sticker. Ta-da! ?

Easy-peasy, isn't it? ?

But wait, let me clarify. We're going to use two models: GPT-4o and DALL·E 3, both from OpenAI. They're hyped, for real! ?

We'll be using the AI/ML API, which provides access to 200 AI models with a single API. Let me briefly tell you about it.

Meet AI/ML API ??

AI/ML API is a game-changing platform for developers and SaaS entrepreneurs looking to integrate cutting-edge AI capabilities into their products. It offers a single point of access to over 200 state-of-the-art AI models, covering everything from NLP to computer vision.

Key Features for Developers:

  • Extensive Model Library: 200 pre-trained models for rapid prototyping and deployment. ?
  • Customization Options: Fine-tune models to fit your specific use case. ?
  • Developer-Friendly Integration: RESTful APIs and SDKs for seamless incorporation into your stack. ?️
  • Serverless Architecture: Focus on coding, not infrastructure management. ☁️

Get Started for FREE ($0 US dollars): aimlapi.com ?

Deep Dive into AI/ML API Documentation (very detailed, can't agree more): docs.aimlapi.com ?

Tech Stack Ingredients ?

We'll use TypeScript, Next.js, React, and Tailwind CSS to build and design our AI Sticker Maker platform.

  • TypeScript is just a programming language—but a really great one! ?
  • Next.js is the React Framework for the web. It enables us to create high-quality web applications with the power of React components. ?
  • React is the library for web and native user interfaces. ?️
  • Tailwind CSS is the best for styling—just build whatever you want, seriously. ?

That was just a quick overview of what we're going to use. Feel free to learn more about each of them here:

  • TypeScript: typescriptlang.org ?
  • Next.js: nextjs.org ⏭️
  • React: react.dev ⚛️
  • Tailwind CSS: tailwindcss.com ?️

Cooking Has Started ?

Let's get our hands dirty! First, create a folder. Open your terminal and enter this:

mkdir aiml-tutorial
cd aiml-tutorial

Now, let's create a new Next.js app:

npx create-next-app@latest

It will ask you a few questions:

What is your project named? Here, you should enter your app name. For example: aistickermaker. For the rest of the questions, simply hit enter.

Here's what you'll see:

✔ Would you like to use TypeScript? … No / Yes
✔ Would you like to use ESLint? … No / Yes
✔ Would you like to use Tailwind CSS? … No / Yes
✔ Would you like your code inside a `src/` directory? … No / Yes
✔ Would you like to use App Router? (recommended) … No / Yes
✔ Would you like to use Turbopack for `next dev`? … No / Yes
✔ Would you like to customize the import alias (`@/*` by default)? … No / Yes

Pro Tip: Feel free to choose Yes or No based on your preferences. I won't judge! ?

Let's open the project with VSCode:

code .

Now, Visual Studio Code should launch directly with this app. Time to start coding! ?

Implementing APIs ?️

First things first, let's create APIs for enhancing the user prompt and generating the sticker. Go to the app folder, then create a new folder called api, and within it, create two new folders: enhancePrompt and generateSticker. For each, create a route.ts file.

The enhancePrompt Endpoint ?‍♂️

Now, let's start with the enhancePrompt endpoint. Open route.ts inside the enhancePrompt folder and enter the following code:

import { NextResponse } from 'next/server';

const systemPrompt = `
You are tasked with enhancing user prompts to generate clear, detailed, and creative descriptions for a sticker creation AI. The final prompt should be imaginative, visually rich, and aligned with the goal of producing a cute, stylized, and highly personalized sticker based on the user's input.

Instructions:

Visual Clarity: The enhanced prompt must provide clear visual details that can be directly interpreted by the image generation model. Break down and elaborate on specific elements of the scene, object, or character based on the user input.

Example: If the user says "A girl with pink hair," elaborate by adding features like "short wavy pink hair with soft, pastel hues."
Style & Theme:

Emphasize that the final output should reflect a cute, playful, and approachable style.
Add terms like "adorable," "cartoonish," "sticker-friendly," or "chibi-like" to guide the output to a lighter, cuter aesthetic.
Include styling prompts like “minimalistic lines,” “soft shading,” and “vibrant yet soothing colors.”
Personalization:

If a reference or context is given, enhance it to make the sticker feel personalized.
Add context-appropriate descriptors like “wearing a cozy blue hoodie,” “soft pink blush on cheeks,” or “a playful expression.”
Expression & Pose:

Where applicable, refine prompts with suggestions about facial expressions or body language. For example, “Smiling softly with big sparkling eyes” or “A cute wink and a slight tilt of the head.”
Background & Accessories:

Optionally suggest simple, complementary backgrounds or accessories, depending on user input. For instance, "A light pastel background with small, floating hearts" or "Holding a tiny, sparkling star."
Colors:

Emphasize the color scheme based on the user's description, making sure it's consistent with a cute, playful style.
Use descriptors like “soft pastels,” “bright and cheerful,” or “warm and friendly hues” to set the mood.
Avoid Overcomplication:

Keep the descriptions short enough to be concise and not overly complex, as the output should retain a sticker-friendly quality.
Avoid unnecessary details that could clutter the design.
Tone and Language:

The tone should be light, imaginative, and fun, matching the playful nature of stickers.

Example:
User Input:
"A girl with pink hair wearing a hoodie."

Enhanced Prompt:
"An adorable girl with short, wavy pink hair in soft pastel hues, wearing a cozy light blue hoodie. She has a sweet smile with big, sparkling eyes, and a playful expression. The sticker style is cartoonish with minimalistic lines and soft shading. The background is a simple light pastel color with small floating hearts, creating a cute and inviting look."
`;

export async function POST(request: Request) {
    try {
        const { userPrompt } = await request.json();
        console.log("/api/enhancePrompt/route.ts userPrompt: ", userPrompt);

        // Make the API call to the external service
          const response = await fetch('https://api.aimlapi.com/chat/completions', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'Authorization': `Bearer ${process.env.NEXT_PUBLIC_AIML_API_KEY}`
            },
            body: JSON.stringify({
              model: 'gpt-4o-mini',
              messages: [
                {
                  role: 'system',
                  content: systemPrompt
                },
                {
                  role: 'user',
                  content: userPrompt
                }
              ]
            })
          });

        console.log("response: ", response);

        if (!response.ok) {
            // If the API response isn't successful, return an error response
            return NextResponse.json({ error: "Failed to fetch completion data" }, { status: response.status });
        }

        const data = await response.json();
        console.log("data: ", data);

        const assistantResponse = data.choices[0]?.message?.content || "No response available";

        // Return the assistant's message content
        return NextResponse.json({ message: assistantResponse });
    } catch (error) {
        console.error("Error fetching the data:", error);
        return NextResponse.json({ error: "An error occurred while processing your request." }, { status: 500 });
    }
}

Here's separated prompt:

You are tasked with enhancing user prompts to generate clear, detailed, and creative descriptions for a sticker creation AI. The final prompt should be imaginative, visually rich, and aligned with the goal of producing a cute, stylized, and highly personalized sticker based on the user's input.

Instructions:

Visual Clarity: The enhanced prompt must provide clear visual details that can be directly interpreted by the image generation model. Break down and elaborate on specific elements of the scene, object, or character based on the user input.

Example: If the user says "A girl with pink hair," elaborate by adding features like "short wavy pink hair with soft, pastel hues."
Style & Theme:

Emphasize that the final output should reflect a cute, playful, and approachable style.
Add terms like "adorable," "cartoonish," "sticker-friendly," or "chibi-like" to guide the output to a lighter, cuter aesthetic.
Include styling prompts like “minimalistic lines,” “soft shading,” and “vibrant yet soothing colors.”
Personalization:

If a reference or context is given, enhance it to make the sticker feel personalized.
Add context-appropriate descriptors like “wearing a cozy blue hoodie,” “soft pink blush on cheeks,” or “a playful expression.”
Expression & Pose:

Where applicable, refine prompts with suggestions about facial expressions or body language. For example, “Smiling softly with big sparkling eyes” or “A cute wink and a slight tilt of the head.”
Background & Accessories:

Optionally suggest simple, complementary backgrounds or accessories, depending on user input. For instance, "A light pastel background with small, floating hearts" or "Holding a tiny, sparkling star."
Colors:

Emphasize the color scheme based on the user's description, making sure it's consistent with a cute, playful style.
Use descriptors like “soft pastels,” “bright and cheerful,” or “warm and friendly hues” to set the mood.
Avoid Overcomplication:

Keep the descriptions short enough to be concise and not overly complex, as the output should retain a sticker-friendly quality.
Avoid unnecessary details that could clutter the design.
Tone and Language:

The tone should be light, imaginative, and fun, matching the playful nature of stickers.

Example:
User Input:
"A girl with pink hair wearing a hoodie."

Enhanced Prompt:
"An adorable girl with short, wavy pink hair in soft pastel hues, wearing a cozy light blue hoodie. She has a sweet smile with big, sparkling eyes, and a playful expression. The sticker style is cartoonish with minimalistic lines and soft shading. The background is a simple light pastel color with small floating hearts, creating a cute and inviting look."

What's Happening Here? ?

  • Importing NextResponse: To handle our HTTP responses smoothly.
  • Defining the POST function: This is where the magic happens when someone hits this endpoint.
  • Fetching the userPrompt: We're grabbing the prompt the user provided.
  • Calling AI/ML API's API: We're making a request to enhance the user's prompt using GPT-4o.
  • Handling Responses: We check if the response is okay, parse the data, and extract the assistant's response.
  • Error Handling: Because nobody likes unhandled errors ruining the party.

Here's an actual example of how the AI enhances the user's prompt. ???

You just entered a prompt:

A cute panda eating ice cream under a rainbow

The AI will enhance it to make it more detailed and visually rich. As a result, you should ger a response like:

An adorable, chibi-like panda with big, sparkling eyes and a joyful expression, savoring a colorful scoop of ice cream. The panda is fluffy and round, with classic black-and-white markings, sitting contentedly. The ice cream cone features vibrant, swirling flavors in pastel pink, mint green, and sunny yellow. Above, a playful, cartoonish rainbow arcs across a soft blue sky, adding a cheerful splash of color. The design is sticker-friendly with minimalistic lines and soft shading, ensuring a cute and delightful aesthetic perfect for capturing the joyful scene.

Alright, let's dive back into the code cauldron and continue cooking up our AI Sticker Maker! ?

The generateSticker Endpoint ?️

So, we've got our enhancePrompt endpoint simmering nicely. Time to spice things up with the generateSticker endpoint. Head over to the api/generateSticker folder and open up route.ts. Replace whatever's in there (probably nothing) with this fresh code:

// api/generateSticker/route.ts
import { NextResponse } from 'next/server';

export async function POST(request: Request) {
    try {
        const { userPrompt } = await request.json();
        console.log("/api/generateSticker/route.ts userPrompt: ", userPrompt);

        // Make the API call to the external service
        const response = await fetch('https://api.aimlapi.com/images/generations', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${process.env.NEXT_PUBLIC_AIML_API_KEY}`
          },
          body: JSON.stringify({
            provider: 'openai',
            prompt: userPrompt,
            model: 'dall-e-3',
            n: 1,
            quality: 'hd',
            response_format: 'url',
            size: '1024x1024',
            style: 'vivid'
          })
        });

        console.log("response: ", response);

        if (!response.ok) {
            // If the API response isn't successful, return an error response
            return NextResponse.json({ error: "Failed to fetch completion data" }, { status: response.status });
        }

        const data = await response.json();
        console.log("data: ", data);

        const assistantResponse = data.data[0]?.url || "No response available";

        console.log("assistantResponse: ", assistantResponse);

        // Return the assistant's message content
        return NextResponse.json({ message: assistantResponse });
    } catch (error) {
        console.error("Error fetching the data:", error);
        return NextResponse.json({ error: "An error occurred while processing your request." }, { status: 500 });
    }
}

What's Happening Here? ?

  • Importing NextResponse: To handle our HTTP responses smoothly.
  • Defining the POST function: This is where the magic happens when someone hits this endpoint.
  • Fetching the userPrompt: We're grabbing the prompt the user provided.
  • Calling AI/ML API's API: We're making a request to generate an image based on the prompt using DALL·E 3.
  • Handling Responses: We check if the response is okay, parse the data, and extract the image URL.
  • Error Handling: Because nobody likes unhandled errors ruining the party.

Let's try above prompt with panda in action! ?

Here's our cutesy panda sticker! ???

Building an AI Sticker Maker Platform with AI/ML API, Next.js, React, and Tailwind CSS using OpenAI GPT-and DALL·E odels.

Other examples ?

Prompt:

A girl with short white grey hair wearing a oversize shirt

Building an AI Sticker Maker Platform with AI/ML API, Next.js, React, and Tailwind CSS using OpenAI GPT-and DALL·E odels.

Prompt:

A girl with short black pink hair wearing a oversize pink shirt

Building an AI Sticker Maker Platform with AI/ML API, Next.js, React, and Tailwind CSS using OpenAI GPT-and DALL·E odels.

Seems, like really WOW! ?

We need a frontend, GUYS! ?

Building the Frontend ?

Time to put a face on our app! Let's create a user interface where users can input their prompt and get a shiny new sticker.

The page.tsx File ?

Navigate to app/page.tsx and update it with the following code:

// app/page.tsx
'use client';

import Image from "next/image";
import { useState } from 'react';
import { faArrowUp, faDownload, faTimes } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import Notification from './utils/notify';
import { Analytics } from "@vercel/analytics/react"

export default function Home() {
  const [notification, setNotification] = useState(null);  // notification message
  const [loading, setLoading] = useState(false);
  const [prompt, setPrompt] = useState('');
  const [stickerUrl, setStickerUrl] = useState("");

  const loader = () => (
    
  );

  const enhanceUserPrompt = async (prompt: string) => {
    setNotification({ message: 'Enhancing user prompt...', type: 'info' });

    // Make the API call to the /api/enhancePrompt route and return the enhanced prompt
    const response = await fetch('/api/enhancePrompt', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ userPrompt: prompt }),
    });

    if (!response.ok) {
      throw new Error('Failed to fetch completion data');
    }

    const data = await response.json();
    return data.message;
  };

  const generateCuteSticker = async (prompt: string) => {
    setNotification({ message: 'Generating cute sticker...', type: 'info' });

    // Make the API call to the /api/generateSticker route and return the generated sticker URL
    const response = await fetch('/api/generateSticker', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ userPrompt: prompt }),
    });

    if (!response.ok) {
      throw new Error('Failed to fetch completion data');
    }

    const data = await response.json();
    return data.message;
  };

    const generateSticker = async () => {
        if (!prompt) return;

        setLoading(true);
        setNotification({ message: 'Processing request...', type: 'info' });

        try {
          // Enhance user prompt
          const enhancedPrompt = await enhanceUserPrompt(prompt);

          if (!enhancedPrompt) {
            setNotification({ message: 'Failed to enhance user prompt.', type: 'error' });
            return;
          }

          // Generate cute sticker
          const sticker = await generateCuteSticker(enhancedPrompt); 

          if (!sticker) {
            setNotification({ message: 'Failed to generate cute sticker.', type: 'error' });
            return;
          }

          setStickerUrl(sticker);
          console.log('Sticker URL:', sticker);
          setNotification({ message: 'Cute sticker generated successfully!', type: 'success' });

        } catch (error) {
          console.error('An unexpected error occurred:', error);
          setNotification({ message: 'An unexpected error occurred.', type: 'error' });
        } finally {
          setLoading(false);
        }
    };

    const handleDownload = () => {
      if (!stickerUrl) return;

      const link = document.createElement('a');
      link.href = stickerUrl;
      link.download = 'cute-sticker.png'; // You can set a default filename
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    };

    const handleClose = () => {
      setStickerUrl("");
      setPrompt("");
    };

    return (
        
{notification && ( setNotification(null)} /> )}

Let's Generate Cutesy AI Sticker!

setPrompt(e.target.value)} placeholder="A girl with short pink hair wearing a oversize hoodie..." className="placeholder:text-[#aeaeae] bg-transparent focus:outline-none text-white outline-none w-full px-4" disabled={loading} />
{/* Modal */} {stickerUrl && (
{/* Download Button */} {/* Close Button */} {/* Sticker Image */}
Generated Sticker
)}
); }

Breaking It Down ?

  • Loader: We are using really simple, but nice loader; three horizontal dots with some nice animaton:
  const loader = () => (
    
  );
  • State Management: Using useState to handle notifications, loading state, the user's prompt, and the sticker URL.
  • Functions:
    • enhanceUserPrompt: Calls our /api/enhancePrompt endpoint to make the user's prompt more... well, prompting.
    • generateCuteSticker: Hits the /api/generateSticker endpoint to get that adorable sticker.
    • generateSticker: Orchestrates the whole process when the user clicks the magic button.
    • handleDownload: Allows the user to download their new sticker.
    • handleClose: Closes the sticker modal.
  • UI Components:
    • Input Field: Where the user types their wildest sticker dreams.
    • Generate Button: Triggers the sticker generation.
    • Modal: Displays the sticker with options to download or close.
    • Notifications: Pops up messages to inform the user what's going on.

A Sprinkle of FontAwesome ?

We're using FontAwesome for icons. Make sure to install it:

npm i --save @fortawesome/fontawesome-svg-core
npm i --save @fortawesome/free-solid-svg-icons
npm i --save @fortawesome/free-regular-svg-icons
npm i --save @fortawesome/free-brands-svg-icons
npm i --save @fortawesome/react-fontawesome@latest

You may also check the FontAwesome documentation for more details. Or search for other icons Search icons.

Handling Notifications ?

Remember that notification component we imported? Let's create it.

Creating the Notification Component ?

Create a new folder called utils inside your app directory. Inside utils, create a file called notify.tsx and paste:

// app/utils/notify.tsx
import React, { useEffect } from 'react';

type NotificationProps = {
  message: string;
  type: 'error' | 'success' | 'info';
  onClose: () => void;
};

const Notification: React.FC = ({ message, type, onClose }) => {
  useEffect(() => {
    const timer = setTimeout(() => {
      onClose();
    }, 3000); // Auto-close after 3 seconds
    return () => clearTimeout(timer);
  }, [onClose]);

  const bgColor = type === 'error' ? 'bg-red-500' : type === 'success' ? 'bg-green-500' : 'bg-blue-500';

  return (
    

{message}

); }; export default Notification;

What's This For? ?

  • Purpose: To display temporary messages to the user, like "Generating cute sticker..." or "An error occurred."
  • Auto-Close Feature: It disappears after 3 seconds, just like my motivation on Monday mornings.
  • Styling: Changes color based on the type of notification.

Configuring Image Domains ?️

Since we're fetching images from OpenAI's servers, Next.js needs to know it's okay to load them. Open up next.config.ts and add:

// next.config.ts
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  /* config options here */
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'oaidalleapiprodscus.blob.core.windows.net',
        port: '',
      },
    ],
  },
};

export default nextConfig;

Why Do This? ?‍♂️

Because Next.js is a bit overprotective (like a helicopter parent) and won't load images from external domains unless you specifically allow it. This setting tells Next.js, "It's cool, these images are with me."

Environment Variables ?

Now, before you excitedly run your app and wonder why it's not working, let's set up our environment variables.

Setting Up Your AI/ML API Key ?️

Create a file called .env.local in the root of your project and add:

NEXT_PUBLIC_AIML_API_KEY=your_api_key_here

Replace your_api_key_here with your actual AI/ML API key. If you don't have one, you might need to sign up at AI/ML API and grab it. It's absolutely FREE to get started!

Here's a Quick Tutorial on how to get your API key: How to get API Key from AI/ML API. Quick step-by-step tutorial with screenshots for better understanding.

Warning: Keep this key secret! Don't share it publicly or commit it to Git. Treat it like your Netflix password.

Fire It Up! ?

Time to see this baby in action.

Running the Development Server ?‍♀️

In your terminal, run:

npm run dev

This starts the development server. Open your browser and navigate to http://localhost:3000.

You should see your AI Sticker Maker platform. ?

Building an AI Sticker Maker Platform with AI/ML API, Next.js, React, and Tailwind CSS using OpenAI GPT-and DALL·E odels.

Testing It Out ?

  • Enter a Prompt: Something like "A girl with short white grey hair wearing a oversize shirt". Go wild!

Building an AI Sticker Maker Platform with AI/ML API, Next.js, React, and Tailwind CSS using OpenAI GPT-and DALL·E odels.

  • Click the Button: Hit that generate button and watch the magic unfold.
  • Wait for It...: You'll see notifications keeping you posted.
  • Voilà!: Your AI-generated sticker should appear. Bask in its glory.

Building an AI Sticker Maker Platform with AI/ML API, Next.js, React, and Tailwind CSS using OpenAI GPT-and DALL·E odels.

Troubleshooting ?️

  • "Failed to fetch completion data": Double-check your API key and make sure it's set correctly.
  • Images Not Loading: Ensure your next.config.ts file is set up as shown above.
  • App Crashes: Open your console and see what errors pop up. Google is your friend!

Wrapping Up ?

Congratulations! You've just built an AI Sticker Maker that's both fun and functional. Not only did you delve into the world of AI and Next.js, but you also made something that can bring a smile to people's faces.

What's Next? ?

  • Styling: Customize the look and feel. Make it as fabulous or minimalist as you like.
  • Features: Add user accounts, sticker galleries, or even a feature to create sticker packs.
  • Monetization: Integrate Stripe and start charging for premium stickers. Time to make some moolah!

Final Thoughts ?

Building this app was like making a sandwich with layers of tech goodness. We've got AI models as the filling, Next.js as the bread, and a sprinkle of humor as the secret sauce.

Remember, the world is your oyster (or sticker). Keep experimenting, keep building, and most importantly, have fun!

Happy coding! ?

Full implementation available on Github AI Sticker Maker.

It’s Absolutely FREE to get started! Try It Now click

Also check out this tutorial, it's very interesting! Building a Chrome Extension from Scratch with AI/ML API, Deepgram Aura, and IndexedDB Integration

Should you have any questions or need further assistance, don’t hesitate to reach out via email at [email protected].

版本声明 本文转载于:https://dev.to/abdibrokhim/building-an-ai-sticker-maker-platform-with-aiml-api-nextjs-react-and-tailwind-css-using-openai-gpt-4o-and-dalle-3-models-46ip?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 了解 MongoDB 的distinct() 操作:实用指南
    了解 MongoDB 的distinct() 操作:实用指南
    MongoDB 的distinct() 操作是一个强大的工具,用于从集合中的指定字段检索唯一值。本指南将帮助您了解distinct() 的用途、使用它的原因和时间,以及如何在 MongoDB 查询中有效地实现它。 什么是distinct()? distinct() 方法返回集合或集合...
    编程 发布于2024-11-07
  • 为什么 JavaScript 中的“0”在比较中为 False,而在“if”语句中为 True?
    为什么 JavaScript 中的“0”在比较中为 False,而在“if”语句中为 True?
    揭开 JavaScript 的悖论:为什么“0”在比较中为假,但在 If 语句中为假在 JavaScript 中,原语 " 的行为0”给开发者带来了困惑。虽然诸如“==”之类的逻辑运算符将“0”等同于假,但“0”在“if”条件下表现为真。比较悖论代码下面演示了比较悖论:"0&qu...
    编程 发布于2024-11-07
  • GitHub Copilot 有其怪癖
    GitHub Copilot 有其怪癖
    过去 4 个月我一直在将 GitHub Copilot 与我们的生产代码库一起使用,以下是我的一些想法: 好的: 解释复杂代码:它非常适合分解棘手的代码片段或业务逻辑并正确解释它们。 单元测试:非常擅长编写单元测试并快速生成多个基于场景的测试用例。 代码片段:它可以轻松地为通用用例生成有用的代码片段...
    编程 发布于2024-11-07
  • 静态类或实例化类:什么时候应该选择哪个?
    静态类或实例化类:什么时候应该选择哪个?
    在静态类和实例化类之间做出选择:概述在 PHP 中设计软件应用程序时,开发人员经常面临在使用静态类或实例化对象。这个决定可能会对程序的结构、性能和可测试性产生重大影响。何时使用静态类静态类适用于对象不具备静态类的场景独特的数据,只需要访问共享功能。例如,用于将 BB 代码转换为 HTML 的实用程序...
    编程 发布于2024-11-07
  • ⚠️ 在 JavaScript 中使用 `var` 的隐藏危险:为什么是时候继续前进了
    ⚠️ 在 JavaScript 中使用 `var` 的隐藏危险:为什么是时候继续前进了
    关键字 var 多年来一直是 JavaScript 中声明变量的默认方式。但是,它有一些怪癖和陷阱,可能会导致代码出现意外行为。现代替代方案(如 let 和 const)解决了许多此类问题,使它们成为大多数情况下声明变量的首选。 1️⃣ 提升:var 在不知不觉中声明变量! ?解释:...
    编程 发布于2024-11-07
  • PDO::MYSQL_ATTR_INIT_COMMAND 需要“SET CHARACTER SET utf8”吗?
    PDO::MYSQL_ATTR_INIT_COMMAND 需要“SET CHARACTER SET utf8”吗?
    在带有“PDO::MYSQL_ATTR_INIT_COMMAND”的 PDO 中“SET CHARACTER SET utf8”是否必要?在 PHP 和 MySQL 中,“SET NAMES” utf8”和“SET CHARACTER SET utf8”通常在使用 UTF-8 编码时使用。但是,当使...
    编程 发布于2024-11-07
  • 为什么使用Password_Hash函数时哈希值会变化?
    为什么使用Password_Hash函数时哈希值会变化?
    了解Password_Hash函数中不同的哈希值在开发安全认证系统时,开发人员经常会遇到使用password_hash获取不同密码哈希值的困惑功能。为了阐明此行为并确保正确的密码验证,让我们分析此函数背后的机制。密码加盐:有意的功能password_hash 函数有意生成唯一的盐它对每个密码进行哈希...
    编程 发布于2024-11-07
  • 为什么与谷歌竞争并不疯狂
    为什么与谷歌竞争并不疯狂
    大家好,我是 Antonio,Litlyx 的首席执行官,我们的对手是一些巨头! Microsoft Clarity、Google Analytics、MixPanel...它们是分析领域的重要参与者。当人们听说一家初创公司正在与如此知名的公司合作时,他们常常会感到惊讶。但让我们看看为什么与谷歌这样...
    编程 发布于2024-11-07
  • 如何在 Java Streams 中高效地将对象列表转换为可选对象?
    如何在 Java Streams 中高效地将对象列表转换为可选对象?
    使用 Java 8 的可选和 Stream::flatMap 变得简洁使用 Java 8 流时,将 List 转换为可选 并有效地提取第一个 Other 值可能是一个挑战。虽然 flatMap 通常需要返回流,但可选的 Stream() 的缺失使问题变得复杂。Java 16 解决方案Java 16 ...
    编程 发布于2024-11-07
  • 避免前端开发失败:编写干净代码的行之有效的实践
    避免前端开发失败:编写干净代码的行之有效的实践
    介绍 您是否曾因看似无法理清或扩展的凌乱代码而感到不知所措?如果你有,那么你并不孤单。许多开发人员面临着维护干净的代码库的挑战,这对于项目的长期成功和可扩展性至关重要。让我们探索一些有效的策略来保持代码可管理性和项目顺利运行。 了解基础知识:什么是干净代码? 干净的...
    编程 发布于2024-11-07
  • 如何访问Python字典中的第一个和第N个键值对?
    如何访问Python字典中的第一个和第N个键值对?
    获取 Python 字典中的第一个条目使用数字索引(如颜色[0])对字典进行索引可能会导致 KeyError 异常。从 Python 3.7 开始,字典保留插入顺序,使我们能够像有序集合一样使用它们。获取第一个键和值要获取字典中的第一个键和值,我们可以使用以下方法:列表转换:使用 list(dict...
    编程 发布于2024-11-07
  • 使用 cProfile 和 PyPy 模块优化 Python 代码:完整指南
    使用 cProfile 和 PyPy 模块优化 Python 代码:完整指南
    介绍 作为 Python 开发人员,我们通常先关注让代码正常运行,然后再担心优化它。然而,在处理大规模应用程序或性能关键型代码时,优化变得至关重要。在这篇文章中,我们将介绍两个可用于优化 Python 代码的强大工具:cProfile 模块和 PyPy 解释器。 在这篇文章的结尾,...
    编程 发布于2024-11-07
  • 上周我学到了什么(
    上周我学到了什么(
    原生 JavaScript 中的反应性 – 使用代理模式在应用程序状态更改时触发事件。 (前端大师课程 - “你可能不需要框架”) throw new Error("Error!") 不能在三元中使用(至少不能用作 'else' 部分。三元运算符的最后一部分...
    编程 发布于2024-11-07
  • 如何在 Linux 系统上将 Java 应用程序作为服务运行?
    如何在 Linux 系统上将 Java 应用程序作为服务运行?
    Linux 系统服务导航:将 Java 应用程序作为服务运行在 Linux 系统管理领域,将应用程序作为服务进行管理对于确保其可靠且受控的执行至关重要。本文深入探讨了将 Java 服务器应用程序配置为在 Linux 操作系统上作为服务运行的过程,为用户提出的问题提供了全面的解决方案。主要目标是创建一...
    编程 发布于2024-11-07
  • 如何在不安装 Angular CLI 的情况下创建 Angular 项目的特定版本
    如何在不安装 Angular CLI 的情况下创建 Angular 项目的特定版本
    您是否使用 Angular 并需要使用不同的 Angular 版本设置项目?这是为特定版本创建 Angular 项目的简单指南,无论是否使用 Angular CLI! 为什么使用特定的 Angular 版本? 在处理多个 Angular 项目时,有时您需要锁定特定版本。也许您的项目依...
    编程 发布于2024-11-07

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3