Unable To Format String – Python

I’m unable to format this string, why is this?

def poem_description(publishing_date, author, title, original_work):
  poem_desc = "The poem {title} by {author} was originally published in {original_work} in {publishing_date}.".format(publishing_date, author, title, original_work)
  return poem_desc

my_beard_description = poem_description("1897", "Tauqeer", "Venice", "1992")

print(my_beard_description)

c# – Replace string based on multiple rules, don’t replace same section twice

Given a 2-column CSV dictionary file that contains translation of certain words, this c# code needs to replace the first occurrence of a word in the dictionary.

  • Once a segment of string has been replaced, it cannot be matched or overwritten by a new dictionary word.

This sounded like a fairly simple task but the code I came up with runs horribly slow and I’m looking for ways to improve it.

All the offending code is in the TestReplace function, I build up a hashset that keeps track of what character Ids in the string have been touched. When you apply a rule that changes the lenght of the string, all the character ids switch around so they have to be recalculated and I believe it costs a lot of performance. Wish there was a simpler way to do this !

Here is a super simple case of what the code tries to do :

Dictionary file:

hello >>> hi

hi >>> goodbye

Input: hello, world!

First rule is applied so string becomes -> hi, world. The word hi is now locked.

Second rule is applied but the string does not become goodbye, world since this part is locked.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace stringReplacer
{
    class Program
    {
        public static Dictionary<string, string> ReplacementRules = new Dictionary<string, string>()
        {
            {"John","Freddy" },
            {"John walks","Freddy runs" },
            {"brown dog","gray dog" },
            {"dog","cat" },
            {"- not -", "(not)" },
            {"(","" },
            {")","" },
            {"whenever",  "sometimes, when"},
            {"raining", "snowing" },
            {"his", "many" }
        };

        static void Main(string() args)
        {
            string Input = "John walks his brown dog whenever it's - not - raining";
            string ExpectedOutput = "Freddy walks many gray dog sometimes, when it's (not) snowing";

            string TestReplaceOutput = TestReplace(Input, ReplacementRules);
            ValidateReplacement("TestReplace", TestReplaceOutput, ExpectedOutput);
        }
        public static string TestReplace(string input, Dictionary<string, string> ReplacementRules)
        {
            HashSet<int> LockedStringSegment = new HashSet<int>();

            foreach (var rule in ReplacementRules)
            {
                string from = Regex.Escape(rule.Key);
                string to = rule.Value;
                var match = Regex.Match(input, from);
                if (match.Success)
                {
                    List<int> AffectedCharacterPositions = Enumerable.Range(match.Index, match.Length).ToList();

                    if (!AffectedCharacterPositions.Any(x => LockedStringSegment.Contains(x)))
                    {
                        input = Regex.Replace(input, from, to);
                        int LengthDelta = to.Length - rule.Key.Length;

                        LockedStringSegment
                            .Where(x => x > match.Index + rule.Key.Length).OrderByDescending(x => x).ToList()
                            .ForEach(x =>
                            {
                                //We shuffle the locked character's place depending on the replacement delta.
                                LockedStringSegment.Remove(x);
                                LockedStringSegment.Add(x + LengthDelta);
                            });

                        //Add all the new locked character's position to the hashset.
                        Enumerable.Range(match.Index, to.Length).ToList().ForEach(x => LockedStringSegment.Add(x));

                    }
                }
            }

            return input;
        }
        public static void ValidateReplacement(string MethodName, string Actual, string Expected)
        {
            Console.Write($"{MethodName} : ");

            if (Expected != Actual)
                Console.WriteLine("String replacement doesn't work");
            else
                Console.WriteLine("It works");

            Console.WriteLine($"Expected : {Expected}");
            Console.WriteLine($"Actual   : {Actual} nn");

        }

    }

}

vue.js – Array in post converts to string

in html if you do

<form action="" method="post">
  <select multiple name="items[]">
    <option value.... 

the post result will be an array. With vue, if you do

<input type="hidden" name="items[]" v-model="myArray">

you get back an array with one element containing a string “1,2,3”. Essentially, v-model converts into a string on the post request. How can I get it to post an actual array?

how to remove everything except {Group} and {Desc} from string variable cardLabel and add a space be

how to remove everything except {Group} and {Desc} from string variable cardLabel and add a space between them in javascript?

I get cardLabel value from database and the value sometimes contain all 6 variables but can contain value with sometimes just 2 variables, sometimes with sometimes just 4 variables. Please note order for the variables can be different and can contain more variables in future.

cardLabel’s dynamic value examples:

cardLabel='{Group} {Desc} – {termMonth} Month – {termOdometer} KMs/Miles {DeductibleAmount} {DeductibleType}’;

cardLabel='{Desc} – {termMonth} Month – {termOdometer} KMs/Miles’;

cardLabel='{Desc} {Group} – {termMonth} Month’;

cardLabel='{Group} {Desc} – {termMonth} Month {DeductibleAmount}’;
SEMrush

I have tried the following code but it is not ideal because the database value can contain more variables in future:
cardLabel = cardLabel.replace(‘{termMonth}’,”).replace(‘{termOdometer}’,”).replace(‘{DeductibleAmount}’,”).replace(‘{DeductibleType}’,”).replace(‘-‘, ”);

The desire end result should be one of the following: cardLabel='{Group} {Desc}’; cardLabel='{Desc} {Group}’;

 

search – WordPress, fetching users with an exact match in a string of comma separated values in user_meta

I have data saved in user_meta -> areapref field. It is basically a string of comma delimited post IDs (e.g. 2, 37, 200, 300 etc.)

I need to check if the user has a particular ID in this field. If so… do stuff.

I can check if an ID is in areapref using LIKE. But I believe this has an issue. If one location is ID=10, and another is ID=100 – both will match with 1, or 10? Or am I misunderstanding LIKE. I fear CONTAIN would have the same issue.

I need to know how to get a list of users who have an ‘exact match’ within the areapref string? So search for ID 2, will return only 2, NOT 22, or 20, 200 etc.
I’ve spent hours going through stackexchange/overflow/wp codex and cannot find an answer… though I am dense!

Here’s enough code I hope to show what I’m currently doing… any ideas greatly appreciated.

function ds_notify_new_event( $post_ID ){
$url = get_permalink( $post_ID );
$event = get_the_title( $post_ID );
$localeID = get_post_field( 'location_id', $post_ID);
global $wpdb;
$locale = $wpdb->get_var( $wpdb->prepare(
" SELECT post_id FROM {$wpdb->prefix}em_locations WHERE ID = %d ",
$localeID ) );

$args = array(
        'role'    => 'subscriber',
        'meta_query' => array(
                array( 'key' => 'areapref', 'value' => $locale, 'compare' => 'LIKE' ),
                // just checks usr is ok with email
                array( 'key' => 'notify', 'value' => 'yes', 'compare' => '=' ) 
            ),
        'fields' => array( 'display_name', 'user_email' )
    );
// retrieve users to notify about the new post
$users = get_users( $args );

// do stuff with users

sharepoint server – Exception in String type error on SPFX with JQuery

I really need help to resolve Type error encountered on this function in SPFX with jQuery.

Here is the function, The return statement is failing:

var addFile = function (fileTitle, fileName, fileType, team) {
var requestUri = "../_api/web/lists/getByTitle('SPFxFiles')/items";
var requestHeaders = {
    "accept": "application/json;odata=verbose",
    "content-type": "application/json;odata=verbose",
    "X-RequestDigest": $('#__REQUESTDIGEST').val()
}
var fileData = {
    __metadata: { "type": "SP.Data.SPFxFilesListItem" },
    Title: fileTitle,
    SPFxFileName: fileName,
    SPFxFileType: fileType,
    SPFxTeam: team
};
var requestBody = JSON.stringify(fileData);
return $.ajax({
    url: requestUri,
    type: "POST",
    headers: requestHeaders,
    data: requestBody
});
{
    "resource": ".../src/webparts/orderForm/OrderFormWebPart.ts",
    "owner": "typescript",
    "code": "2769",
    "severity": 8,
    "message": "No overload matches this call.n  Overload 1 of 2, '(url: string, settings?: AjaxSettings<any>): jqXHR<any>', gave the following error.n    Argument of type '{ url: string; type: string; contentType: string; headers: { accept: string; "X-HTTP-Method": string; "X-RequestDigest": string | number | string(); "If-Match": string | number | string(); }; data: string; }' is not assignable to parameter of type 'string'.n  Overload 2 of 2, '(settings?: AjaxSettings<any>): jqXHR<any>', gave the following error.n    Type '{ accept: string; "X-HTTP-Method": string; "X-RequestDigest": string | number | string(); "If-Match": string | number | string(); }' is not assignable to type 'PlainObject<string>'.n      Property '"X-RequestDigest"' is incompatible with index signature.n        Type 'string | number | string()' is not assignable to type 'string'.n          Type 'number' is not assignable to type 'string'.",
    "source": "ts",
    "startLineNumber": 317,
    "startColumn": 8,
    "endLineNumber": 323,
    "endColumn": 3,
    "relatedInformation": (
        {
            "startLineNumber": 165,
            "startColumn": 13,
            "endLineNumber": 165,
            "endColumn": 20,
            "message": "The expected type comes from property 'headers' which is declared here on type 'AjaxSettings<any>'",
            "resource": ".../node_modules/@types/jquery/misc.d.ts"
        }
    )
}

programming languages – Why didn’t == operator string value comparison make it to Java?

Consistency within the language. Having an operator that acts differently can be surprising to the programmer. Java doesn’t allow users to overload operators – therefore reference equality is the only reasonable meaning for == between objects.

Within Java:

  • Between numeric types, == compares numeric equality
  • Between boolean types, == compares boolean equality
  • Between objects, == compares reference identity
    • Use .equals(Object o) to compare values

That’s it. Simple rule and simple to identify what you want. This is all covered in section 15.21 of the JLS. It comprises three subsections that are easy to understand, implement, and reason about.

Once you allow overloading of ==, the exact behavior isn’t something that you can look to the JLS and put your finger on a specific item and say “that’s how it works,” the code can become difficult to reason about. The exact behavior of == may be surprising to a user. Every time you see it, you have to go back and check to see what it actually means.

Since Java doesn’t allow for overloading of operators, one needs a way to have a value equality test that you can override the base definition of. Thus, it was mandated by these design choices. == in Java tests numeric for numeric types, boolean equality for boolean types, and reference equality for everything else (which can override .equals(Object o) to do whatever they want for value equality).

This is not an issue of “is there a use case for a particular consequence of this design decision” but rather “this is a design decision to facilitate these other things, this is a consequence of it.”

String interning, is one such example of this. According to the JLS 3.10.5, all string literals are interned. Other strings are interned if one invokes .intern() on them. That "foo" == "foo" is true is a consequence of design decisions made to minimize the memory footprint taken up by String literals. Beyond that, String interning is something that is at the JVM level that has a little bit of exposure to the user, but in the overwhelming vast majority of cases, should not be something that concerns the programmer (and use cases for programmers wasn’t something that was high on the list for the designers when considering this feature).

People will point out that + and += are overloaded for String. However, that is neither here nor there. It remains the case that if == has a value equality meaning for String (and only String), one would need a different method (that only exists in String) for reference equality. Furthermore, this would needlessly complicate methods that take Object and expect == to behave one way and .equals() to behave another requiring users to special case all those methods for String.

The consistent contract for == on Objects is that it is reference equality only and that .equals(Object o) exists for all objects which should test for value equality. Complicating this complicates far too many things.

sql server – conversion failed when converting datetime from character string while inserting and updating to database

I’m trying to insert time and date separately and calculate if it is late to the set time and then insert it to database…

here’s my try code for update

string Date = DateTime.Now.ToString(“dd-MM-yyyy”);
string Time = DateTime.Now.ToString(“h:mm:ss tt”);
SqlCommand comm2 = conn.CreateCommand();
comm2.CommandText = “Update Time_Logs SET Time_Out = ‘” + Time + “‘ where Emp_Id = ‘” + EmpId.Text + “‘ and Date = ‘” + Date + “‘”;
try
{
conn.Open();
comm2.ExecuteNonQuery();
MessageBox.Show(“Time_Out…”);
conn.Close();
TimeCompute();
}
catch (Exception x)
{
MessageBox.Show(x.Message);
conn.Close();
}

and here is the code for inserting

string Date = DateTime.Now.ToString(“dd-MM-yyyy”);
string Time = DateTime.Now.ToString(“h:mm:ss tt”);

        SqlCommand comm = conn.CreateCommand();
        comm.CommandText = "INSERT INTO Time_Logs (Emp_Id, Date, Time_In) VALUES('" + EmpId.Text + "','" + Date + "','" + Time + "')";
        try
        {
            conn.Open();
            comm.ExecuteNonQuery();
            MessageBox.Show("Time_In...");
            conn.Close();
            DateTime time = DateTime.Parse(Time);
            DateTime inDate = DateTime.Parse("8:00:00 AM");
            TimeSpan ts1 = inDate.TimeOfDay;
            TimeSpan ts = time - inDate;
            if (ts < ts1)
            {
                SqlCommand comm2 = conn.CreateCommand();
                comm2.CommandText = "Update Time_Logs SET Late = '" + ts + "' where Emp_Id = '" + EmpId.Text + "' and Date = '" + Date + "'";
                conn.Open();
                comm2.ExecuteNonQuery();
                conn.Close();
            }
            else
            {
                SqlCommand comm2 = conn.CreateCommand();
                comm2.CommandText = "Update Time_Logs SET Late = '" + ts + "' where Emp_Id = '" + EmpId.Text + "' and Date = '00:00:00'";
                conn.Open();
                comm2.ExecuteNonQuery();
                conn.Close();
            }
        }
        catch (Exception x)
        {
            MessageBox.Show(x.Message);
            conn.Close();
        }

Pasando codigo VB.NET a c# con Strings.mid y otras funciones String

Hola qué tal? estoy hace 2 horas y media intentando pasar el siguiente códigode VB.NET a c#

 temp = Mid(codigodebarrasingresa, InStr(1, mascara, "I"), InStrRev(mascara, "I") - InStr(1, mascara, "I") + 1)
 importedeterminado = CDec(Left(temp, Len(temp) - 2) & "," & Right(temp, 2))
 codigoproductoreal = Mid(codigodebarrasingresa, InStr(1, mascara, "P"), InStrRev(mascara, "P") - InStr(1, mascara, "P") + 1)

Todas las variables anteriormente declaradas son String, No encuentro las equivalencias en c# y las que pude encontrar no hace exactamente lo mismo, realmente es un mapa del tesoro pasar estas lineas, alguien podría darme una respuesta?
No sé exactamente cuáles puedan ser las equivalencias de las variables Strings.Left y demás en c#
Desde ya muchas gracias