c++ – How can I remove the duplicated code in this code?

this is some function:

RequestResult MenuRequestHandler::joinRoom(RequestInfo requestInfo)
{
    RequestResult requestResult;
    JoinRoomRequest joinRoomReq;
    joinRoomReq = JsonRequestPacketDeserializer::deserializeJoinRoomRequest(requestInfo.buffer);
    JoinRoomResponse joinRoomRes;

    if (this->m_roomManager.isRoomExists(joinRoomReq.roomId) &&
        !this->m_roomManager.getRoomState(joinRoomReq.roomId) &&
        !this->m_roomManager.isRoomFull(joinRoomReq.roomId)) 
    {
        joinRoomRes.status = 1;

        this->m_roomManager.addUserToRoom(this->m_user, joinRoomReq.roomId);
        try {
            requestResult.newHandler = m_handlerFactory->createRoomMemberRequestHandler(m_user, this->m_roomManager.getRoomDataById(joinRoomReq.roomId));
        }
        catch (MyException& e) {
            Log(e.what());
            // *this*
            joinRoomRes.status = 0;
            // *and this*
            requestResult.newHandler = nullptr;
        }
    }
    else {
        // *appear here*
        joinRoomRes.status = 0;
        // *and here*
        requestResult.newHandler = nullptr;
    }
    
    requestResult.buffer = JsonResponsePacketSerializer::serializeResponse(joinRoomRes);
    return requestResult;
}

i want to remove the duplicated code but i can’t figure out a way to do it.
it tried another way but that’s another duplicated code, like this:

RequestResult MenuRequestHandler::joinRoom(RequestInfo requestInfo)
{
    RequestResult requestResult;
    JoinRoomRequest joinRoomReq;
    joinRoomReq = JsonRequestPacketDeserializer::deserializeJoinRoomRequest(requestInfo.buffer);
    JoinRoomResponse joinRoomRes;

    if (this->m_roomManager.isRoomExists(joinRoomReq.roomId) &&
        !this->m_roomManager.getRoomState(joinRoomReq.roomId) &&
        !this->m_roomManager.isRoomFull(joinRoomReq.roomId)) 
    {
        joinRoomRes.status = 1;

        this->m_roomManager.addUserToRoom(this->m_user, joinRoomReq.roomId);
        try {
            requestResult.newHandler = m_handlerFactory->createRoomMemberRequestHandler(m_user, this->m_roomManager.getRoomDataById(joinRoomReq.roomId));
            // *this below*
            requestResult.buffer = JsonResponsePacketSerializer::serializeResponse(joinRoomRes);
            return requestResult;
        }
        catch (MyException& e) {
            Log(e.what());
        }
    }

    joinRoomRes.status = 0;
    requestResult.newHandler = nullptr;
    // *appear here below*
    requestResult.buffer = JsonResponsePacketSerializer::serializeResponse(joinRoomRes);
    return requestResult;
}
```

Duplicated transactions on Google Analytics 4

I`m in a process migrating my Ecommerce from UA to GA4. In this process, the system of GA4 start to duplicate some transactions. That happends when a user reload the thank you page. To solve it, I implement a cookie to block this duplicated transactions with the steps indicated in this page: https://www.bounteous.com/insights/2020/09/02/duplicate-transaction-blocker-recipe/ I also including a new variable in GTM who takes the type of navigation, to divide in navigation, reload and back_forward. What else can i do? nothing works!

theming – jQuery dialog is duplicated when set on a form that uses AJAX

Im using jQuery dialog on my form.

Drupal.behaviors.custom = {
attach: function (context, settings) {

    $('.form-container').once('form-cont', function () {
      Drupal.custom.modalLinks();
    });

    $('.my-form').once('my-form', function () {
       Drupal.custom.setModal(this);
    });

);

  Drupal.custom.modalLinks = function () {
    $('body').on('click', '.modal-link', function (e) {
      var id = $(this).data('modal-id');
      var className = $(this).data('modal-class');
      var $modal = $('.modal--' + id);

      $modal.dialog('widget').
        addClass('modal__wrap--' + className).
        addClass('modal__wrap');
      $modal.dialog('open');

      e.preventDefault();
    });
  };

Drupal.custom.setModal = function (container) {

    var $container = $(container);

    $container.find('.my-modal').
      dialog({
        autoOpen: false,
        draggable: false,
        width: 900,
        minHeight: 120,
        modal: true
    });

};

This is working fine when the page is first loaded. However my form has AJAX submission. When submitted the form then returns a new form which also has a dialog modal link.

If I submit the form then when it reloads with AJAX then the jQuery dialog modal is duplicated (not visible but I can see with dev tools). If I open the dialog now then 2 modals are opened.

From reading about duplicate dialogs (but not for Drupal specifically) it seems the solution is to use remove or destroy on the modal. However when I try this is always completely disables the modal, it doesn’t just remove the duplicates.
https://stackoverflow.com/questions/2864740/jquery-how-to-completely-remove-a-dialog-on-close

python – Avoiding Duplicated Code Fragments Graphene in FastAPI

How can I avoid repeating code fragments between the mutations and types with graphene in a FastAPI app? I really want to avoid repeating any codes for obvious reasons.

graphqlmutations.py

import graphene

from models.customers import CustomerLogin,  CustomerLogin_PydanticIn
from graphql.types import CustomerLoginType


class CreateUserMutation(graphene.Mutation):
    class Arguments:
        id = graphene.Int()
        shard_id = graphene.Decimal()
        seq_num = graphene.Decimal()
        event_timedate = graphene.DateTime()
        user_id = graphene.UUID()
        device_token = graphene.UUID()
        user_ip = graphene.String()
        user_agent = graphene.String()
        client_id = graphene.String()
        process = graphene.String()
        auth_result = graphene.String()
        auth_fail_cause = graphene.String()
        plain_email = graphene.String()

    user = graphene.Field(CustomerLoginType)

    @staticmethod
    async def mutate(parent, info, user: CustomerLogin_PydanticIn):
        user = await CustomerLogin.create(**user.dict())
        return CreateUserMutation(user=user)

graphqltypes.py

import graphene


# Fields should coincide with model.CustomerLogin
class CustomerLoginType(graphene.ObjectType):
    id = graphene.Int()
    shard_id = graphene.Decimal()
    seq_num = graphene.Decimal()
    event_timedate = graphene.DateTime()
    user_id = graphene.UUID()
    device_token = graphene.UUID()
    user_ip = graphene.String()
    user_agent = graphene.String()
    client_id = graphene.String()
    process = graphene.String()
    auth_result = graphene.String()
    auth_fail_cause = graphene.String()
    plain_email = graphene.String()

graphqlqueries.py

import graphene

from models.customers import CustomerLogin
from graphql.types import CustomerLoginType


class Query(graphene.ObjectType):

    all_customer_logins = graphene.List(CustomerLoginType)
    single_customer_login = graphene.Field(CustomerLoginType, id=graphene.Int())

    @staticmethod
    async def resolve_all_customer_logins(parent, info):
        users = await CustomerLogin.all()
        return users

    @staticmethod
    async def resolve_single_customer_login(parent, info, id):
        user = await CustomerLogin.get(id=id)
        return user

Then the ORM model using TortoiseORM

modelscustomers.py

from tortoise import fields
from tortoise.contrib.pydantic import pydantic_model_creator
from tortoise.models import Model

from models.events import ShardID, SequenceNum


class CustomerLogin(Model):
    shard_id: fields.ForeignKeyNullableRelation(ShardID) = 
        fields.ForeignKeyField(model_name='models.ShardID',
                               related_name='customerlogin_shardid',
                               to_field='shard_id',
                               on_delete=fields.RESTRICT,
                               null=True)
    seq_num: fields.ForeignKeyNullableRelation(SequenceNum) = 
        fields.ForeignKeyField(model_name='models.SequenceNum',
                               related_name='customerlogin_seqnum',
                               to_field='seq_num',
                               on_delete=fields.RESTRICT,
                               null=True)
    event_timedate = fields.DatetimeField(null=True)
    user_id = fields.UUIDField(null=True)
    device_token = fields.UUIDField(null=True)
    user_ip = fields.CharField(256, null=True)
    user_agent = fields.CharField(1024, null=True)
    client_id = fields.CharField(256, null=True)
    process = fields.CharField(256, null=True)
    auth_result = fields.CharField(256, null=True)
    auth_fail_cause = fields.CharField(256, null=True)
    plain_email = fields.CharField(256, null=True)


CustomerLogin_Pydantic = pydantic_model_creator(CustomerLogin, name='CustomerLogin')
CustomerLogin_PydanticIn = pydantic_model_creator(CustomerLogin, name='CustomerLoginIn', exclude_readonly=True)

dnd 5e – At what level are spells duplicated by the Wish spell cast?

Wish is a 9th level spell, one of the uses written into it is:

The basic use of this spell is to duplicate any other spell of 8th level or lower. You don’t need to meet any requirements in that spell, including costly components. The spell simply takes effect.

The question is what level is that copy of the spell cast at? I can see three possibilities here:

  • Wish was cast from a 9th level spell slot, so the copied spell is cast at 9th level.
  • Wish can cast up to an 8th level spell as a copy, so the copy cast is cast as if it were using an 8th level slot.
  • The spell being copied is of Nth level, so the copy is cast as if it were using an Nth level slot.

There are good reasons to cast low level spells at higher levels, the extra die per level of healing for cure wounds, the extra missile per level for magic missile, etc, so using a 9th level slot to cast a low level spell copy at the low level would generally be undesirable, but the wish spell isn’t clear.

The first two possibilities both make some sense and are useful, in the 9th level example you just get the spell as if you had cast it normally in the slot, in the 8th level example you’re sacrificing one level of casting bonuses for the ability to cast possibly unknown, unprepared or cross-class spells (no restriction against copying say cleric spells as a wizard with wish) – and that utility seems like a fair trade off.

But which is ‘officially’ correct?

c++ – Read strings from a standard input, and find the most duplicated word

  • Write a program to read strings from standard input looking for duplicated words.
  • The program should find places in the input where one word is followed immediately by itself.
  • Keep track of the largest number of times a single repetition occurs and which word is repeated.
  • Print the maximum number of duplicates, or else print a message saying that no word was repeated.

For example, if the input is

  • how now now now brown cow cow

the output should indicate that the word now occurred three times.


#include <iostream>
#include <string>

int main()
{
    using std::cin; using std::cout; using std::endl;
    using std::string;

    // running median
    string most_duplicated_str;
    int most_duplicated_count = 0;

    // loop variables
    string prev_str;
    string new_str;
    int new_duplicate_count = 1;

    while(cin >> new_str)
    {
        if (new_str != prev_str)
        {
            // check and update median
            if (new_duplicate_count > most_duplicated_count)
            {
                most_duplicated_str = prev_str;
                most_duplicated_count = new_duplicate_count;
            }

            // update prev_str
            new_duplicate_count = 1;
            prev_str = new_str;
            continue;
        }

        ++new_duplicate_count;
        prev_str = new_str;
    }

    // check and update median for last word
    if (new_duplicate_count > most_duplicated_count)
    {
        most_duplicated_str = prev_str;
        most_duplicated_count = new_duplicate_count;
    }

    // print result
    if(most_duplicated_count == 0)
        cout << "# No Duplicated Words #n";
    else
        cout << "Most duplicated word: " << most_duplicated_str << ", " << most_duplicated_count << " times.n";
}

sharepoint online – JSON – how to highlight duplicated items in a specific column?

ID column should always be updated by code or it should be autgenerated to reduce the duplication.

Currently JSON Formatter only work with formation and changing the layout of data.

But Still if you want check the dublicate value and highlight it. Customization is required.

In order to fullfill this requirment you have to use SharePoint Extension – Field Customizer and in item level you can build your logic.

mysql – Delete all duplicated entries where multiple columns duplicates match

I need to add this contrain to my table called ‘kraken’

ALTER TABLE kraken ADD UNIQUE unique_index(exchange_pair,timestamp);

this shows me that i have duplicated entries on those 2 columns (exchange_pair and timestamp)
so first i have to delete all the duplicated entries based on those 2 columns

this is what i found but im not sure if my query would work, i dont want to mess things up with my table
https://www.mysqltutorial.org/mysql-delete-duplicate-rows/

object oriented – A Paragraph Merger with Removing Overlapped Duplicated Lines in C#

I am trying to make a paragraph merger that takes multiple paragraphs and output a concatenated result with removing the duplicated overlapped lines due to redundancy. Each input paragraph is with the follows specifications.

The output merged paragraph follows the rules as below.

  • Paragraph input to Update method is concatenated after the previous input.

  • If the line(s) from the start of the paragraph input to Update method is / are sequenced same (overlapped) as the end of the previous input, just keep single copy of the sequenced duplicated lines.

  • The definition of duplicated lines here:

    • The content in two line should be totally the same, no “partial overlapping” cases need to be considered.

    • The content sequence in two blocks of lines should be totally the same.

Example Input and Output

Besides the rules, here’s a use case.

  • Inputs

    Input paragraph 1 example:

    Code Review is a question and answer site for seeking peer review of your code.
    It's built and run by you as part of the Stack Exchange network of Q&A sites.
    We're working together to improve the skills of programmers worldwide by taking working code and making it better.
    We're a little bit different from other sites. Here's how:
    Ask questions, get answers, no distractions
    This site is all about getting answers.
    It's not a discussion forum.
    There's no chit-chat.
    

    Input paragraph 2 example:

    We're a little bit different from other sites. Here's how:
    Ask questions, get answers, no distractions
    This site is all about getting answers.
    It's not a discussion forum.
    There's no chit-chat.
    Good answers are voted up and rise to the top.
    The best answers show up first so that they are always easy to find.
    The person who asked can mark one answer as "accepted".
    Accepting doesn't mean it's the best answer, it just means that it worked for the person who asked.
    Get answers to practical, detailed questions
    Focus on questions about an actual problem you have faced.
    Include details about what you have tried and exactly what you are trying to do.
    
  • Expected Output

    enter image description here

    The two block of text are the same, so keep single overlapped part after merging.

    enter image description here

    Code Review is a question and answer site for seeking peer review of your code.
    It's built and run by you as part of the Stack Exchange network of Q&A sites.
    We're working together to improve the skills of programmers worldwide by taking working code and making it better.
    We're a little bit different from other sites. Here's how:
    Ask questions, get answers, no distractions
    This site is all about getting answers.
    It's not a discussion forum.
    There's no chit-chat.
    Good answers are voted up and rise to the top.
    The best answers show up first so that they are always easy to find.
    The person who asked can mark one answer as "accepted".
    Accepting doesn't mean it's the best answer, it just means that it worked for the person who asked.
    Get answers to practical, detailed questions
    Focus on questions about an actual problem you have faced.
    Include details about what you have tried and exactly what you are trying to do.
    

The experimental implementation

The experimental implementation is as below.

(Serializable)
class ParagraphMerger
{
    private List<string> paragraphContents;

    public ParagraphMerger(List<string> input)
    {
        this.paragraphContents = input;
    }

    public ParagraphMerger(string() input)
    {
        this.paragraphContents = input.ToList();
    }

    public ParagraphMerger Update(List<string> input)
    {
        return Update(input.ToArray());
    }

    public ParagraphMerger Update(string() input)
    {
        bool flag = false;
        foreach (var element in input)
        {
            if (((!IsStringExist(paragraphContents, element)) || flag) && (!String.IsNullOrWhiteSpace(element)))
            {
                paragraphContents.Add(element);
                flag = true;
            }
        }
        return this;
    }

    public override string ToString()
    {
        StringBuilder sb = new StringBuilder();
        foreach (var element in this.paragraphContents)
        {
            sb.AppendLine(element);
        }
        return sb.ToString();
    }

    private bool IsStringExist(List<string> strings, string target)
    {
        if (strings is null)
        {
            return false;
        }
        if (target is null)
        {
            throw new ArgumentNullException();
        }
        foreach (var element in strings)
        {
            if (element.Equals(target))
            {
                return true;
            }
        }
        return false;
    }
}

Test cases

The test case here use ParagraphMerger class with File.ReadAllText and File.WriteAllText. The content of “paragraph1.txt” is as “Input paragraph 1” above and “paragraph2.txt” is as “Input paragraph 2” above.

var paragraph1 = File.ReadAllText("paragraph1.txt").Split(new() { Environment.NewLine }, StringSplitOptions.None);
var paragraph2 = File.ReadAllText("paragraph2.txt").Split(new() { Environment.NewLine }, StringSplitOptions.None);

ParagraphMerger paragraphMerger = new ParagraphMerger(paragraph1);
paragraphMerger.Update(paragraph2);

File.WriteAllText("output.txt", paragraphMerger.ToString());
Console.WriteLine(paragraphMerger.ToString());

All suggestions are welcome. If there is any issue about:

  • Data processing performance

  • The naming and readability

  • Potential drawbacks of the implemented methods

, please let me know.

linux – msys:fixing pacman errors (“duplicated database entry” and /var/lib/pacman/local/… No such file or directory”

For some reason my pacman install on msys is flaking out. Running pacman -Syuu:

:: Synchronizing package databases...
 mingw32 is up to date
 mingw64 is up to date
 msys is up to date
:: Starting core system upgrade...
error: duplicated database entry 'mingw-w64-x86_64-bzip2'
error: duplicated database entry 'mingw-w64-x86_64-gcc-libs'
error: duplicated database entry 'mingw-w64-x86_64-gettext'
error: duplicated database entry 'mingw-w64-x86_64-gmp'
error: duplicated database entry 'mingw-w64-x86_64-libffi'
error: duplicated database entry 'mingw-w64-x86_64-libiconv'
error: duplicated database entry 'mingw-w64-x86_64-libwinpthread-git'
error: duplicated database entry 'mingw-w64-x86_64-mpc'
error: duplicated database entry 'mingw-w64-x86_64-openssl'
error: duplicated database entry 'mingw-w64-x86_64-pcre'
error: duplicated database entry 'mingw-w64-x86_64-python'
error: duplicated database entry 'mingw-w64-x86_64-xz'
error: duplicated database entry 'mingw-w64-x86_64-zlib'
 there is nothing to do
:: Starting full system upgrade...
resolving dependencies...
looking for conflicting packages...
error: could not open file /var/lib/pacman/local/mingw-w64-x86_64-openssl-1.1.1.h-1/files: No such file or directory
warning: could not fully load metadata for package mingw-w64-x86_64-openssl-1.1.1.h-1
error: failed to prepare transaction (invalid or corrupted package)

I’d be fine to just wipe out /var/lib/pacman/local and rebuild/download it or whatever, but I can’t find any command lines to do so. Is there a way to restore my database without reinstalling msys?