2022-12-31

convert a string of a math formula to Object Tree in Javascript?

a function that converts a math string passed as a prop (with the operations +, -, /, *)
by returning an object that contains pieces of the math string, in an ordered/better way easier to loop on it then.

test cases if you need them:

Example 1: Basic Math (same operation)

N Input (string) Output (object)
1 1 { values: [1], operation: null }
2 1+1 { values: [1,1], operation: "+" }
3 1+2+3 { values: [1,2,3], operation: "+" }
4 3-2-1 { values: [3,2,1], operation: "-" }
5 10*80 { values: [10,80], operation: "*" }
6 100/10 { values: [100,10], operation: "/" }

Example 2: Formula with 2 operations

➡️ + and - samples

N1

input: 1+1-1

output:

{
    values: [
      {
        values: [1, 1],
        operation: "+",
      },
      1,
    ],
    operation: "-",
};

N2

input: 3+2-1+5

output:

{
    values: [
      {
        values: [
          {
            values: [3, 2],
            operation: "+",
          },
          1,
        ],
        operation: "-",
      },
      5,
    ],
    operation: "+",
};

N3

input: 3+2-1+5+10+7

output:

{
    values: [
      {
        values: [
          {
            values: [3, 2],
            operation: "+",
          },
          1,
        ],
        operation: "-",
      },
      5,
      10,
      7
    ],
    operation: "+",
};

➡️ + and / samples

N4

input: 1+2/3

output:

{
    values: [
      1,
      {
        values: [2, 3],
        operation: "/",
      },
    ],
    operation: "+",
};

N5

input: 2/3+1

output:

{
    values: [
      {
        values: [2, 3],
        operation: "/",
      },
      1,
    ],
    operation: "+",
};

N6

input: 1/2+3/4+5/6

output:

{
    values: [
      {
        values: [1, 2],
        operation: "/",
      },
      {
        values: [3, 4],
        operation: "/",
      },
      {
        values: [5, 6],
        operation: "/",
      },
    ],
    operation: "+",
};

N7

input: 1/2/3/4/5+6+7+8/9+10/11

output:

{
    values: [
      {
        values: [1, 2, 3, 4, 5],
        operation: "/",
      },
      6,
      7,
      {
        values: [8, 9],
        operation: "/",
      },
      {
        values: [10, 11],
        operation: "/",
      },
    ],
    operation: "+",
};

➡️ / and - samples

N8

input: 1-2/3

output:

{
    values: [
      1,
      {
        values: [2, 3],
        operation: "/",
      },
    ],
    operation: "-",
};

➡️ / and * samples

N9

input: 10/2*5

output:

{
    values: [
      {
        values: [10, 2],
        operation: "/",
      },
      5,
    ],
    operation: "*",
};

Example 3: Formula with 4 operations

N1

input: 10/2*5+1-1*5/3+2*4

output:

{
    values: [
      {
        values: [
          {
            values: [10, 2],
            operation: "/",
          },
          5,
        ],
        operation: "*",
      },
      1,
      {
        values: [
          {
            values: [-1, 5],
            operation: "*",
          },
          3,
        ],
        operation: "/",
      },
      {
        values: [2, 4],
        operation: "*",
      },
    ],
    operation: "+",
};

Example 4: Formula with () parenthesis

...



Coud not convert Java to Kotlin from IntelliJ [closed]

I tried to convert some Java source files to Kotlin from IntelliJ IDEA Community Edition. I open my Java source file in the IDE, right click on the file name tab, select Convert Java File to Kotlin File.

The IDE responds with a dialogue box telling me that Kotlin is not configured in the project and that I will have to configure Kotlin before performing a conversion.

I select the button labelled "OK, configure Kotlin in the project". The IDE responds with another dialogue box asking me to accept the Kotlin compiler and runtime version. Although the version disclosed in the attached screen shot says 1.8.0-RC2, I have selected 1.8.0 from the drop down menu, and I still receive the same result as what is stated below.

I accept the settings displayed in this dialogue box by selecting the button labelled "OK".

The IDE appears to show me all of the Gradle build files that were altered by the addition of the Kotlin library to them, but does not appear to alter the Jave file that I selected. I have to reopen the Java file in the editor to check this.

Again, I right click on the file name tab of the Java File's editor pane, select the Convert Java File to Kotlin File option, and I get first given dialogue box stated earlier. I select "OK, configure Kotlin in the project", and I am now confronted with another dialogue box advising me that Kotlin is not configured in the project because there are no "configurators" available.

Again, my file was not converted, and the dialogue box produced above wasn't very helpful, so I right clicked on the "clique-space" project's name in the Project pane and selected "Analyse Dependencies...". This is the output I received:

2022-12-26T22:34:39.111+1100 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] FAILURE: Build failed with an exception.
2022-12-26T22:34:39.111+1100 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] 
2022-12-26T22:34:39.111+1100 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] * Where:
2022-12-26T22:34:39.111+1100 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] Build file '/home/x/Development/CliqueSpace/Current/Code/trunk/clique-space/clique-space-concept/build.gradle' line: 2
2022-12-26T22:34:39.111+1100 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] 
2022-12-26T22:34:39.111+1100 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] * What went wrong:
2022-12-26T22:34:39.111+1100 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] Error resolving plugin [id: 'org.jetbrains.kotlin.jvm', version: '1.8.0-RC2']
2022-12-26T22:34:39.111+1100 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] > The request for this plugin could not be satisfied because the plugin is already on the classpath with an unknown version, so compatibility cannot be checked.
2022-12-26T22:34:39.111+1100 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] 
2022-12-26T22:34:39.111+1100 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] * Try:
2022-12-26T22:34:39.111+1100 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] > Run with --stacktrace option to get the stack trace.
2022-12-26T22:34:39.111+1100 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] > Run with --scan to get full insights.
2022-12-26T22:34:39.111+1100 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] 
2022-12-26T22:34:39.111+1100 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] * Get more help at https://help.gradle.org
2022-12-26T22:34:39.111+1100 [ERROR] [org.gradle.internal.buildevents.BuildResultLogger] 
2022-12-26T22:34:39.111+1100 [ERROR] [org.gradle.internal.buildevents.BuildResultLogger] BUILD FAILED in 219ms

When I build this project from the multiproject build script, I get the following output:

cd /home/x/Development/CliqueSpace/Current/Code/trunk/clique-space; ./gradlew --configure-on-demand -x check clean build
Configuration on demand is an incubating feature.

FAILURE: Build failed with an exception.

* Where:
Script '/home/x/Development/CliqueSpace/Current/Code/trunk/clique-space/clique-space-concept/build.gradle' line: 2

* What went wrong:
Error resolving plugin [id: 'org.jetbrains.kotlin.jvm', version: '1.8.0-RC2']
> The request for this plugin could not be satisfied because the plugin is already on the classpath with an unknown version, so compatibility cannot be checked.

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 79ms

My Gradle multiproject root build file named clique-space has the following contents:

  1 subprojects {
  2    apply plugin: 'java'
  3
  4 repositories {
  5     mavenCentral()
  6    }
  7 }
  8 buildscript {
  9     ext.kotlin_version = '1.8.0'
 10     repositories {
 11         mavenCentral()
 12     }
 13     dependencies {
 14         classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
 15     }
 16 }
 17 apply plugin: 'kotlin'
 18 repositories {
 19     mavenCentral()
 20 }
 21 dependencies {
 22     implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
 23 }
 24 compileKotlin {
 25     kotlinOptions {
 26         jvmTarget = "1.8"
 27     }
 28 }
 29 compileTestKotlin {
 30     kotlinOptions {
 31         jvmTarget = "1.8"
 32     }
 33 }

Line 17 in this build scrips seems out of place. I think this line should go in the subprojects section below line 2. So, I've moved it there so the file looks like this:

  1 subprojects {
  2     apply plugin: 'java'
  3     apply plugin: 'kotlin'
  4 
  5     repositories {
  6         mavenCentral()
  7     }
  8 }
  9 buildscript {
 10     ext.kotlin_version = '1.8.0'
 11     repositories {
 12         mavenCentral()
 13     }
 14     dependencies {
 15          classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
 16     }
 17 }
 18 repositories {
 19     mavenCentral()
 20 }
 21 dependencies {
 22     implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
 23 }
 24 compileKotlin {
 25     kotlinOptions {
 26         jvmTarget = "1.8"
 27     }
 28 }
 29 compileTestKotlin {
 30     kotlinOptions {
 31         jvmTarget = "1.8"
 32     }
 33 }

Now, although I am not sure if this is an improvement or a further screw up (some guidance would be great!), I get the following message when I try to build the clique-space project:

A problem occurred evaluating root project 'clique-space'.
> Could not find method implementation() for arguments [org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.8.0] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.

* Try:
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

I am at a complete loss. The only thing obvious to me is that the IntelliJ claim that it can easily convert Java to Kotlin is false. Help me find the answer to why this is going awry and you'll get a tick from me. Thanks.

Perhaps what I need to do is to abandon my current build script because it uses outdated and unsupported features of Gradle, and create a new project. Apart from the pious finger wagging (which isn't help, but equanimity by people who, without an answer, shouldn't be interacting with my question), there is absolutely no help to be had here on crap overfow! None at all!

A philosophy that admits "asking the wrong question" as a reasonable starting point for offering help to others is, at best, an exercise of wilful ignorance that bleeds into conceit.


Is there any credence in the suspicion that Kotlin (named after an island in Russian territory offshore from St Petersburg) may become a victim of Russia's war on Ukraine? Are my troubles with the language a symptom of this victimisation? Perhaps I should stick with Java (which works fine) for now?



Which time-complexity is better O(logM + logN) or O(logM.logN)?

I tried the binary search on the 2D matrix and I got the solution which gives the time compexity to be the O(logN.logM). There exist already a solution which performs it in log(MN) time. I Only want to know which is better or less-time taking. Really a burning question.



Reference to array of objects in Sanity

Im having issues with references in Sanity. Im setting some color themes in the root of my Sanity schema:

defineField({
      name: 'articletheme',
      title: 'Article theme',
      description: 'Create 4 themes for article blocks',
      type: 'array',
      validation: (Rule) => Rule.required(),
      of: [{ type: 'articleThemeBlock' }],
    }),

In one of the blocks I would like to reference the theme array to select which color theme that block should use.

Ive tried this, but it fails:

defineField({
      name: 'theme',
      title: 'Theme',
      type: 'reference',
      to: [
        {
          type: 'array',
          of: [
            {
              type: 'articletheme',
            },
          ],
        },
      ],
    }),

Any suggestions?



How to compare variable name and button id to load content inside variable for ThreeJS?

I am using Three.js to load multiple 3D models and store them in an array in the background. I've multiple buttons with unique ID add that specific model to scene. Now I want to compare the button ID and variable name so that I can load only that specific model and remove any other models added to the scene. I have written a for loop to to loop through all the variable to compare with ID of the clicked button, but I'm not able to access only variable name so that I can compare it with button ID.

Following is my code :

function modelShow() {

  let m;

  var models =  [mandi_0, maxi_0, mandi_1, maxi_1, mandi_2, maxi_2];

  for (m = 0; m < models.length; m++) {

    if(models[m].name == event.target.id){
      scene.add(models[m]);
    }
    else {
      scene.remove(models[m]);
    }
  }
}

let j;

for (j = 0; j < buttons.length; j++) {
   buttons[j].addEventListener('click', modelShow);
} 

How can I compare only variable name with button ID and not the content inside variable?



2022-12-30

How do I mirror an NSAttributedString with an icon and text in right-to-left mode

I have a UIButton that holds an NSAttributedString that contains an icon (which is an NSAttributedString itself) followed by a text.

It looks something like this:

Button appearance in LTR

I want to make it look like this when the device is configured for an RTL language (e.g. Arabic, Hebrew):

Desired look in RTL mode

The string is built like this:

var iconText = NSAttributedString(fontName: fontName, fontSize: fontPointSize, fontValue: fontValue, color: color ?? iconColor)
let iconTextRange = NSRange(location: 0, length: iconText.count)
let iconAttrs: [NSAttributedString.Key: Any] = [.font: icon.font(pointSize: pointSize),
                                                .foregroundColor: iconColor]

if !text.isEmpty {
    iconText = "\(iconText) \(text)"
}

let attributeString = NSMutableAttributedString(string: iconText, attributes: textAttrs)
attributeString.addAttributes(iconAttrs, range: iconTextRange)
return attributeString

As you can see, first the icon is created using a font, then it's concatenated to the text.

In other parts of the app, I managed to make NSAttributedString's RTL-compliant with this little piece of code:

public extension NSAttributedString {
    /// Returns an identical attributed string that'll adjust its direction based on the device's configured language.
    func rightToLeftAdjusted() -> NSAttributedString {
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.baseWritingDirection = .natural
        
        let attrs: [NSAttributedString.Key: Any] = [.paragraphStyle: paragraphStyle]
        let range = NSRange(location: 0, length: length)
        
        let copy = NSMutableAttributedString(attributedString: self)
        copy.addAttributes(attrs, range: range)
        
        return copy
    }
}
    

Unfortunately, in this specific case, it doesn't seem to work, the star ALWAYS stays to the left of the text.

Are there any other ways of achieving this?



Unable to Send Word Mail Merge Email in VBA Due to Word File not Opening

I have a table in access and a Word mail merge setup and linked to the table. I would like my customers to receive an email on a specific date stated in the table. I have created a template in word and started the mail merge process using the step-by-step mail merge wizard ready for VBA to send the email. I have tried this VBA code in Access, but it just keeps crashing and I think it is because it can't open the Word file. I am sure of this as I commented out the code line by line and it only crashed when I put Set wdDoc = wdApp.Documents.Open("C:\Users\Adam Khattab\Documents\Mail Merge - Copy.docx"). I reviewed this this post, however, this is specifically for Access and not Excel.

Option Compare Database

Sub SendEmailsWord()

Const wdSendToEmail As Long = 0

Const wdMailFormatPlainText As Long = 2

On Error GoTo ErrorHandler

'Declare variables

Dim wdApp As Word.Application

Dim wdDoc As Word.Document

Dim strSQL As String

Dim rst As DAO.Recordset

'Set the reference to the Word application

On Error Resume Next

Set wdApp = GetObject(, "Word.Application")

On Error GoTo 0

If wdApp Is Nothing Then

  Set wdApp = CreateObject("Word.Application")

End If

'Open the mail merge document

Set wdDoc = wdApp.Documents.Open("C:\Users\Adam Khattab\Documents\Mail Merge - Copy.docx")

'Set the reference to the recordset

strSQL = "SELECT * FROM CustomerBookingTBL WHERE EmailAddress IS NOT NULL"

Set rst = CurrentDb.OpenRecordset(strSQL)

'Start the mail merge

wdDoc.MailMerge.OpenDataSource "C:\Users\Adam Khattab\Documents\Customer_Bookings_Backup.accdb", strSQL

'Loop through the recordset and send each email

Do Until rst.EOF

    wdDoc.MailMerge.Destination = wdSendToEmail

    wdDoc.MailMerge.SuppressBlankLines = True

    With wdDoc.MailMerge

        .MailFormat = wdMailFormatPlainText

        .MailSubject = "Mail Merge Subject"

        .MailAsAttachment = False

        .MailAddressFieldName = "EmailAddress"

        .Execute Pause:=False

    End With

    rst.MoveNext

Loop

'Close the mail merge document

wdDoc.Close False

'Close the Word application

wdApp.Quit

Exit Sub

ErrorHandler:

  MsgBox "An error occurred: " & Err.Description

End Sub


How to transfer ERC1155 token using web3 Python?

I believe this subject will help many other people, i searched a lot and did not find anything clear.

I've been researching this for days, but i can't find a solution.

I need to transfer an ERC1155 token using python.

Something very simple, send token from account1 to account2 using python.

Token: ERC 1155 Network: Polygon Language: Python

Could someone please leave an example how to do it.

Thanks

from web3 import Web3
import json

rpc_polygon = "https://polygon-rpc.com"

web3 = Web3(Web3.HTTPProvider(rpc_polygon))
# print(web3.isConnected())

account_1 = "FROM_ADDRESS"
account_2 = "TO_ADDRESS"

private_key = "PRIVATE_KEY_HERE"

balance = web3.eth.get_balance(account_1)
humanReadable = web3.fromWei(balance, 'ether')
print(f'balance: {humanReadable}')

nonce = web3.eth.get_transaction_count(account_1)
# print(f'nonce: {nonce}')

ABI = json.loads('[{"inputs":[{"internalType":"address","name":"_logic","type":"address"},{"internalType":"address","name":"admin_","type":"address"},{"internalType":"bytes","name":"_data","type":"bytes"}],"stateMutability":"payable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"previousAdmin","type":"address"},{"indexed":false,"internalType":"address","name":"newAdmin","type":"address"}],"name":"AdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"beacon","type":"address"}],"name":"BeaconUpgraded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"implementation","type":"address"}],"name":"Upgraded","type":"event"},{"stateMutability":"payable","type":"fallback"},{"inputs":[],"name":"admin","outputs":[{"internalType":"address","name":"admin_","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newAdmin","type":"address"}],"name":"changeAdmin","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"implementation","outputs":[{"internalType":"address","name":"implementation_","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newImplementation","type":"address"}],"name":"upgradeTo","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newImplementation","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"upgradeToAndCall","outputs":[],"stateMutability":"payable","type":"function"},{"stateMutability":"payable","type":"receive"}]')

interactedContract = '0xba6666b118f8303f990f3519df07e160227cce87'
TOKEN_ID = '7'

# token = 'https://polygonscan.com/token/0xba6666b118f8303f990f3519df07e160227cce87?a=7#writeProxyContract#F7'

amount_humanReadable = 1
amount = web3.toWei(amount_humanReadable, 'ether')
# print(amount)

web3.eth.account.privateKeyToAccount(private_key)

checksumAddress = Web3.toChecksumAddress(interactedContract)
# print(checksumAddress)

contract = web3.eth.contract(address=checksumAddress, abi=ABI)

txn_hash = contract.functions.transfer(account_2, TOKEN_ID, amount).transact()
txn_receipt = web3.eth.waitForTransactionReceipt(txn_hash)
print(txn_receipt)

if txn_receipt.status:
    print("Transfer successful")
else:
    print("Transfer failed")

Error message: web3.exceptions.ABIFunctionNotFound: ("The function 'safeTransactFrom' was not found in this contract's abi. ", 'Are you sure you provided the correct contract abi?')



Acquire/Release Visibility of Latest Operation

There is a lot of subtlety in this topic and so much information to sift through. I couldn't find an existing question/answer that specifically addressed this question, so here goes.


If I have an atomic variable M of type std::atomic_int, where

  1. Thread 1 performs M.store(1, memory_order_release)
  2. Later, Thread 2 performs M.store(2, memory_order_release)
  3. Even later, Thread 3 M.load(memory_order_acquire)

Is there any legitimate scenario in which Thread 3 could read the value 1 instead of 2?

My assumption is that it is impossible, because of write-write coherence and happens-before properties. But having spent an hour going over the C++ standard as well as cppreference, I still can't form a concise and definitive answer to this question.

I'd love to get an answer here with credible references. Thanks in advance.



How can I loop a nested json and show all the data in the laravel blade

Actually I am having trouble looping a complex JSON. look at this JSON structure.

{
    "transactionId": "blablablabla",
    "campaigns": [
        {
            "affiliateNumbers": [
                {
                    "phoneNumber": "+345345",
                    "localNumber": "(888) 34534534534-456456",
                    "displayNumber": "6345345345",
                    "assignmentSettings": {
                        "countryCode": "US",
                        "isTollFree": true,
                        "limit": 5
                    },
                    "deallocFlag": false,
                    "failedRechargeAttempts": 0,
                    "isCarrierNumber": false,
                    "carrierNumberId": "",
                    "isInternalOnly": false,
                    "affiliate": {
                        "accountId": "546546",
                        "id": "asddasdasd",
                        "subId": "",
                        "createNumbers": false,
                        "userIds": [
                            "475f197a-d05d-41ce-adf8-17e4fe430e46"
                        ],
                        "isSelf": false,
                        "isCriteriaInverted": false,
                        "name": "Poshnee tech SMC PVT LTD",
                        "enabled": true,
                        "version": 1
                    }
                }
            ]
        }
    ]
}

I tried so many times I am not going to include my code cause I am really ashamed of getting laughed at. So what I want is to loop this JSON and show it in a Laravel blade.php file. How can I achieve that? IS there any easy solution for me?

Here is my Controller:

public function fetch_all_campaigns(): \Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Contracts\Foundation\Application
{
    $headers = [
        "Content-Type" => "application/json",
        "Authorization" => "Token ****"
    ];

    $campaigns = Http::get(
        "https://api.ringba.com/v2/XXXXXXXXXXXXXXXXXXX/campaigns",
        $headers
    );

    return view("Dashboard.Campaigns.campaigns", [
        "campaigns" => $campaigns
    ]);
}


Identity Db Context Get Null In Web API

I have created API in .net 7.0, I have EF core with IdentityDbContext. Problem is when I am going to find user by user manager as below get null exception.

System.Data.SqlTypes.SqlNullValueException: Data is Null. This method or property cannot be called on Null values.
at Microsoft.Data.SqlClient.SqlDataReader.GetFieldValueFromSqlBufferInternal\[T\](SqlBuffer data, \_SqlMetaData metaData, Boolean isAsync)
at Microsoft.Data.SqlClient.SqlDataReader.GetFieldValueInternal\[T\](Int32 i, Boolean isAsync)
at Microsoft.Data.SqlClient.SqlDataReader.GetFieldValue\[T\](Int32 i)

I have tried to get user in login action.

[HttpPost]
[Route("login")]
[AllowAnonymous]
public async Task<IActionResult> Login([FromBody] LoginModel model)
{

    var user = await userManager.FindByNameAsync(model.UserName);

    if (user != null && await userManager.CheckPasswordAsync(user, model.Password))
    {
        var userRoles = await userManager.GetRolesAsync(user);

        var authClaims = new List<Claim>
        {
           new Claim(ClaimTypes.Name, user.UserName),
           new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
        };

        foreach (var userRole in userRoles)
        {
            authClaims.Add(new Claim(ClaimTypes.Role, userRole));
        }
        var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:SecretKey"]));
        var token = new JwtSecurityToken(
        issuer: _configuration["JWT:ValidIssuer"],
        audience: _configuration["JWT:ValidAudience"],
        expires: DateTime.Now.AddHours(3),
        claims: authClaims,
        signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256)
        );
        return Ok(new
        {
            token = new JwtSecurityTokenHandler().WriteToken(token),
            expiration = token.ValidTo
        });
    }
    return Unauthorized();
}


2022-12-29

How Next.js useRouter() handle the mapping variable?

 const router = useRouter();
  return (
    <>
      {Usercategory.map((user,index)=>{
        return <div className='user-li' key={index} onClick={()=>{router.push(user.link)}}>
                <li> 
                  {user.icon}
                </li>
                <li>
                  <span>{user.name}</span>
                  <span>{user.entry}</span>
                </li>
               </div>
      })}
    </>
  )
}

On above ,

onClick={()=>{router.push(user.link)}

Couldn't work ?

How can I finish this? Thanks



Return np.average from masked numpy array [closed]

Fisheye All Sky Images


Idea: Only Calculate with Sky Area Pixels (Solarpoweranalysis)

e.g. static circle

def get_sky_area(radius, centre, image_name):
    img = Image.open(str(image_name))
    cv2_img = np.array(img)
    cv2_img = cv2.cvtColor(cv2_img, cv2.COLOR_RGB2BGR)
    sky = cv2_img.copy()
    mask = np.zeros(sky.shape[:2], dtype="uint8")
    cv2.circle(mask, centre, radius, 255, -1)
    # apply the mask to our image
    masked = cv2.bitwise_and(sky, sky, mask=mask)
    avgR = np.mean(masked[:,:,0])
    avgG = np.mean(masked[:,:,1])
    avgB = np.mean(masked[:,:,2])
    print("Mean of channel R: ", avgR)
    print("Mean of channel G: ", avgG)
    print("MEan of channel B: ", avgB)
    
    #cv2.imshow("sky", sky)
    #cv2.imshow("mask", mask)
    #cv2.imwrite('sky_image.png', masked[:,:,2])
    print("Saved Sky image as sky_image")
    #cv2.imshow("Mask applied to image", masked)
    #cv2.waitKey()
    return avgR, avgG, avgB

Is there smarter way for calculating with masked matric entries?

    CENTRE= (574, 335)
    RADIUS = 353   
    IMAGE_NAME = "path/to/1669190042.jpg" #saved in utc_time_format
    avgR, avgG, avgB = get_sky_area(radius = RADIUS, centre = CENTRE, image_name=IMAGE_NAME)


python compare strings return difference

Consider this sample data:

str_lst = ['abcdefg','abcdefghi']

I am trying to write a function that will compare these two strings in this list and return the difference, in this case, 'hi'

This attempt failed and simply returned both strings.

def difference(string1, string2):
    # Split both strings into list items
    string1 = string1.split()
    string2 = string2.split()

    A = set(string1) # Store all string1 list items in set A
    B = set(string2) # Store all string2 list items in set B
 
    str_diff = A.symmetric_difference(B)
    # isEmpty = (len(str_diff) == 0)
    return str_diff

There are several SO questions claiming to seek this, but they simply return a list of the letters that differ between two strings where, in my case, the strings will have many characters identical at the start and I only want the characters near the end that differ between the two.

Ideas of how to reliably accomplish this? My exact situation would be a list of very similar strings, let's say 10 of them, in which I want to use the first item in the list and compare it against all the others one after the other, placing those differences (i.e. small substrings) into a list for collection.

I appreciate you taking the time to check out my question.

Some hypos:

The strings in my dataset would all have initial characters identical, think, directory paths:

sample_lst = ['c:/universal/bin/library/file_choice1.zip', 
'c:/universal/bin/library/file_zebra1.doc',
'c:/universal/bin/library/file_alpha1.xlsx']

Running the ideal function on this list would yield a list with the following strings:

result = ['choice1.zip', 'zebra1.doc', 'alpha1.xlsx']

Thus, these are the strings that remaining when you remove any duplicate characters at the start of all of the three lists items in sample_lst



Sweetalert2 text property doesn't pass ngModel value

Hello i am trying to pass a value (1 or 2 or 3) from input using NgModel through Sweetalert2 and it's text property but the value is always 0 Any help?

here is the code

    reason: number = 0;
    btn1: any;
    btn2: any;
    btn3: any;

    const steps = ['1', '2', '3']
        const Queue = Swal.mixin({
          progressSteps: steps,
          backdrop:false,
          confirmButtonText: 'Next >',
          customClass: 'height-auto',
          // optional classes to avoid backdrop blinking between steps
          showClass: { backdrop: 'swal2-noanimation' },
          hideClass: { backdrop: 'swal2-noanimation' }
        })
        
        await Queue.fire({
          title: '<b style="font-size:17px!important;">' + this.translation.first_select_why_you_want_to_block_this_member + '</b><br />',
            html: '<br /><ion-textx [(ngModel)]="btn1" [ngClass]="btn1" id="btn1" [value]="1"><a tabindex="1">' + this.translation.rude_or_inappropriate_language + '</a></ion-textx>' + '<br /><br />' +
              '<ion-textx [(ngModel)]="btn2" [ngClass]="btn2" id="btn2" [value]="3"><a tabindex="1">' + this.translation.fake_or_spam_profile + '</a></ion-textx>' + '<br /><br />' +
              '<ion-textx [(ngModel)]="btn3" [ngClass]="btn3" id="btn3" [value]="2"><a tabindex="1">' + this.translation.violent_or_strange_behaviour + '</a></ion-textx>' + '<br /><br />',
          currentProgressStep: 0,
        })
          .then((result: any) => {
              if (this.btn1) {
              this.reason = 1;
            }
            else if (this.btn2) {
              this.reason = 2;
            }
            else if (this.btn3) {
              this.reason =  3;
            }

if (result.value) {
                  Swal.fire({
                    title: this.translation.are_you_sure_you_want_to_send_this_report,
                    backdrop: false,
                    confirmButtonText: '<b style="font-family:Arial;color: whitesmoke;font-size:15px">' +this.translation.send_your_repost+ '</b>',
                  }).then(() => {
                    let report = {
                      reason: this.reason,
                    };

user.module.ts

import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';

import { IonicModule } from '@ionic/angular';

import { UserPageRoutingModule } from './user-routing.module';

import { UserPage } from './user.page';
import { LazyLoadImageModule } from 'ng-lazyload-image';
import { ComponentsModule } from 'src/app/components/components.module';
import { PipesModule } from 'src/app/pipes/pipes.module';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IonicModule,
    UserPageRoutingModule,LazyLoadImageModule,
    ComponentsModule,
    PipesModule
  ],
  declarations: [UserPage],
  schemas:[CUSTOM_ELEMENTS_SCHEMA]
})
export class UserPageModule {}

I want to ask why the value isn't passed with the ngModel. It should be 1 or 2 or 3.

I could be a that i haven't inserted the Ngmodule or ionicModule in user.module.ts but i did. Anything else?

I know that i have to keep the value before it goes to the next step but how do i do that? I tried onRender but it shows an error that i cannot use onRender on the latest swal2



Convert Linq operation syntax to query syntax

I'm trying to figure out how to convert this method syntax into query syntax:

result.Select(c => { c.property1 = 100; return c; }).ToList();


2022-12-28

Stream/Encode videos using Azure Media Services and Node Js

I have an application that uses AWS Elastic Transcoder to encode videos uploaded to S3 buckets into HLS streaming formats using Lambda functions :

var AWS = require('aws-sdk');
var eltr = new AWS.ElasticTranscoder({ apiVersion: '2012–09–25', region: 'ap-south-1' });

exports.handler = function (event, context) {
    var key = event.Records[0].s3.object.key;
    let srcKey = decodeURIComponent(key.replace(/\+/g, " ")); //the object may have spaces  
    let newKey = key.split('.')[0].replace('protected-video-input/', '')

    eltr.createJob({
        PipelineId: pipelineId,
        OutputKeyPrefix: 'protected-video-output/' + newKey + '/',
        Input: {
            Key: srcKey,
            FrameRate: 'auto',
            Resolution: 'auto',
            AspectRatio: 'auto',
            Interlaced: 'auto',
            Container: 'auto'
        },
        Outputs: [
            {
                Key: newKey + '_64k_audio',
                PresetId: '1351620000001-200071',
                SegmentDuration: "10"
            },
            {
                Key: newKey + '_360',
                PresetId: '1593703351160-e26c00',
                SegmentDuration: "10"
            },
            {
                Key: newKey + '_480',
                PresetId: '1593703253941-idqn5g',
                SegmentDuration: "10"
            },
            {
                Key: newKey + '_720',
                PresetId: '1593702727032-5klbqi',
                SegmentDuration: "10"
            },
            {
                Key: newKey + '_1080',
                PresetId: '1593702631383-73kckt',
                SegmentDuration: "10"
            },
            {
                Key: newKey + '.mp4',
                PresetId: '1351620000001-000020'
            },
        ],
        Playlists: [
            {
                Format: 'HLSv3',
                Name: newKey,
                OutputKeys: [
                    newKey + '_64k_audio',
                    newKey + '_360',
                    newKey + '_480',
                    newKey + '_720',
                    newKey + '_1080'
                ]
            }
        ]
    });
};
  • This lambda function converts the videos uploaded to the S3 bucket (now replaced with Azure Blob Storage) into streaming formats (HLS / .m3u8) with different video quality levels (380p, 480p, 720p, 1080p).
  • Currently, I am tasked with migrating all resources used in this application from AWS to Azure, and I am a novice with Azure Services.
  • From my research, I have identified Azure Media Services as an alternative to AWS Elastic Media Encoder.

I replaced the S3 bucket with Azure Blob Storage in order to upload my video files.

Please help with ANY of the following :

  1. Any examples of which method/function of Azure Media Services should I use for converting to HLS format in node js?
  2. Should the videos be stored in Blob Storage or Media Services Assets?


Deploy ERC20Upgradeable without Proxy for governable upgrades

I've created an UUPS upgrade able token (minified for the example)

contract GovernanceToken is Initializable, ERC20Upgradeable, ERC20PermitUpgradeable, ERC20VotesUpgradeable, OwnableUpgradeable, UUPSUpgradeable {
    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() {
        _disableInitializers();
    }

    function initialize() initializer public {
        __ERC20_init("GovernanceToken", "GT");
        __ERC20Permit_init("GovernanceToken");
        __ERC20Votes_init();
        __Ownable_init();
        __UUPSUpgradeable_init();
    }

    //...
}

My deploy script looks like this:

const deployGovernanceToken: DeployFunction = async function (hre: HardhatRuntimeEnvironment) {
  // @ts-ignore
  const { getNamedAccounts, deployments, network } = hre
  const { deploy, save, log, get } = deployments
  const { deployer } = await getNamedAccounts()

  const governanceTokenContractFactory = await ethers.getContractFactory(GOVERNANCE_TOKEN_NAME);
  
  const deployedProxy = await upgrades.deployProxy(governanceTokenContractFactory, [], {
    initializer: "initialize",
    kind: "uups",
  });

  await deployedProxy.deployed();
    
  const governanceToken = await governanceTokenContractFactory.attach(
      deployedProxy.address
  );

  const timeLock = await get(TIMELOCK_CONTROLLER_NAME)
  const governanceTokenContract = await ethers.getContractAt(GOVERNANCE_TOKEN_NAME, governanceToken.address)

  const transferTx = await governanceTokenContract.transferOwnership(timeLock.address)
  await transferTx.wait(1)
}

I would like to upgrade my token, however it's owned by the timelock so I cannot upgrade it from hardhat, so I'd like to deploy another version of the token so I can upgrade it though governance.

This is my upgrade script:

const { getNamedAccounts, deployments, network } = hre
const { deploy, log } = deployments
const { deployer } = await getNamedAccounts()
const timelockAddress = '0x...'

const governanceTokenV2 = await ethers.getContractFactory(GOVERNANCE_TOKEN_NAME);
const governanceTokenContract = await governanceTokenV2.deploy();

log(`Upgraded Token at ${governanceTokenContract.address}`)
   
const owner = await governanceTokenContract.owner();
log(`Verified Token at ${governanceTokenContract.address}`)
log(`owner: ${owner}`)

When I run this I get an error:

Deploying governanceToken and waiting for confirmations... Upgraded Token at 0x5Fb... owner: 0x0000000000000000000000000000000000000000

Error HH604: Error running JSON-RPC server: ERROR processing C:..\deploy\00-deploy-upgraded-Token.ts: Error: VM Exception while processing transaction: reverted with reason string 'Ownable: caller is not the owner'

The token I'm deploying claims the owner is the ZERO_ADDRESS, perhaps this is because the storage is usually associated with the proxy?

How can I deploy this token and transfer ownership to the proxy?

Note: I've tried calling the initialize method, and it claims it's already been initialized



Android app xml resources with variable in it?

Is there a technique to implement the Android app xml resources with variable in it?

For example: I have a app resource, i.e., res/drawable/rounded_corners.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <solid android:color="@android:color/holo_blue_dark" />
    <corners android:radius="10dp" />
</shape>

It works, but I need to change the color in the runtime without creating a lot of similar resources like this just with different colors.



Disable form field google script

I have a link that leads to a prefilled Google form, the prefilled form is editable and user can change the entries

I added a note not to change anything but of course user still has a capability to change it if they want to.

Is there a way to lock or restrict the user from editing the prefilled form?

The user need to see the fields with the prefilled content, but they should not be able to edit/modify it.



Network Graph is displayed without colored nodes

I am trying to run the DSATUR algorithm on a graph but the problem is that the result is displayed with the default color. Dsatur is an algorithm that colors the vertices that have the highest degree of saturation, that is to say that it is the vertex that has the maximum number of colored neighbors.

The algorithm I use comes from the NetworkX documentation, i tried another algorithm like the 'strategy_largest_first' which returns the list of nodes in decreasing order by degree and it works like so many other algorithms dealing with graph problems. So I think the problem might comes from how I display my graph, i.e. nx.draw(G, with_labels=True).

import matplotlib.pyplot as plt
import networkx as nx
import tkinter
from tkinter import *

node_colors = {
    0: (255, 0, 0),
    1: (0, 255, 0),
    2: (200, 20, 128),
    3: (127, 127, 127),
    4: (152, 53, 91),
    5: (44, 200, 100),
    6: (100, 44, 200),
    'null': (0, 0, 0),  # Default Color
    'OOB': (180, 200, 10),  # Color to denote that the node is "Out of bounds" or cannot be colored.
}
Gr = nx.Graph()
Gr.add_node("A")
Gr.add_node("B")
Gr.add_node("F")
Gr.add_node("P")
Gr.add_node("U")


Gr.add_edge("A", "B")
Gr.add_edge("Z", "B")
Gr.add_edge("A", "P")
Gr.add_edge("U", "B")
Gr.add_edge("Z", "F")


def strategy_saturation_largest_first(G, colors):
    """Iterates over all the nodes of ``G`` in "saturation order" (also
    known as "DSATUR").

    ``G`` is a NetworkX graph. ``colors`` is a dictionary mapping nodes of
    ``G`` to colors, for those nodes that have already been colored.

    """
    distinct_colors = {v: set() for v in G}
    for i in range(len(G)):
        # On the first time through, simply choose the node of highest degree.
        if i == 0:
            node = max(G, key=G.degree)
            yield node
            # Add the color 0 to the distinct colors set for each
            # neighbors of that node.
            for v in G[node]:
                distinct_colors[v].add(0)
        else:
            # Compute the maximum saturation and the set of nodes that
            # achieve that saturation.
            saturation = {
                v: len(c) for v, c in distinct_colors.items() if v not in colors
            }
            # Yield the node with the highest saturation, and break ties by
            # degree.
            node = max(saturation, key=lambda v: (saturation[v], G.degree(v)))
            yield node
            # Update the distinct color sets for the neighbors.
            color = colors[node]
            for v in G[node]:
                distinct_colors[v].add(color)

strategy_saturation_largest_first(Gr, node_colors)

nx.draw(Gr, with_labels=True)
plt.margins(0.1)
plt.show()


2022-12-27

Sankey diagram with ggplot

I am relatively experienced in pivoting tables, however this one is almost driving me mad. I want to generate a Sankey plot with flows connecting parameters between two experiments. This is very simple, yet I cannot figure out how the package wants the data laid out.

Please consider the following MWE:

tribble(
~parm, ~value,
"b1", 0.009,
"g1", 0.664,
"b2", 0.000,
"ra", 0.000,
"rc", 0.000,
"ax", 0.084,
"cx", 0.086,
"ex", 0.179,
"ay", 0.045,
"cy", 0.043,
"ey", 0.102
) -> doc1

doc2 <- tribble(
  ~parm, ~value,
  "b1", 0.181,
  "g1", 0.289,
  "b2", 0.181,
  "ra", 0.000,
  "rc", 0.000,
  "ax", 0.001,
  "cx", 0.001,
  "ex", 0.002,
  "ay", 0.001,
  "cy", 0.001,
  "ey", 0.002,
  "re", 0.000,
  "rf", 0.000,
  "b3", 0.289
)


doc1 <- doc1 %>% mutate(model = "exp")
doc2 <- doc2 %>% mutate(model = "exp2")
finalpow <- doc1 %>% full_join(doc2)
a <- pivot_wider(finalpow, names_from = model, values_from = value)

finalpow  <- a%>% make_long( exp, exp2) 

And the following code to generate the diagram:

ggplot(finalpow, aes(x = x,
               next_x = next_x,
               node = node,
               next_node = next_node,
               fill = factor(node),
               label = node)) +
  geom_sankey(flow.alpha = 0.5, node.color = 1) +
  geom_sankey_label(size = 3.5, color = 1, fill = "white") +
  scale_fill_viridis_d() +
  theme_sankey(base_size = 16) +
  guides(fill = guide_legend(title = "Title"))

I am close, as the two bars are the experiments as desired. But the labels should be the different parameters names ax, cx, ex, ... and the "barplots" should be proportional to each parameter values. Here is what I get:

enter image description here



Remove OR replace faulty paragraph marks using VBA macro

I have some faulty paragraphs, which are causing my other macros to not work properly.

  1. They are usually heading style 2, style 3
  2. Empty (not sure)
  3. before OR after table (not sure)
  4. surrounded by dotted line
  5. causes the heading and next table to merged together (not sure)

I tried to replace/removed those with the following macro:

Sub HeadingParaBug()
    Dim H As Range
    Set H = ActiveDocument.Range
    LS = Application.International(wdListSeparator)
    
    With H.Find
        
        .Text = "^p "
        .Replacement.Text = "^p"
        .Execute Replace:=wdReplaceAll
        
        .Text = " ^p"
        .Replacement.Text = "^p"
        .Execute Replace:=wdReplaceAll
        
        .Text = "^p ^p"
        .Replacement.Text = "^p^p"
        .Execute Replace:=wdReplaceAll
        
        .Text = "^13{2" & LS & "}"
        .Replacement.Text = "^p"
        .MatchWildcards = True
        .Execute Replace:=wdReplaceAll
        .Text = ""
        .Style = wdStyleHeading2
        .MatchWildcards = False
    Do While .Execute
    If H.Text <> vbCr Then
        H.Collapse 0
        H.Select
        H.InsertParagraph
        H.Delete
    End If
        H.Collapse 0
    Loop
    End With
    
    Set H = ActiveDocument.Range
    
    With H.Find
        .Style = wdStyleHeading3
    Do While .Execute
    If H.Text <> vbCr Then
        H.Collapse 0
        H.Select
        H.InsertParagraph
        H.Delete
    End If
        H.Collapse 0
    Loop
    
    End With
    
End Sub

But somehow, it do not completely removed/replace the faulty paragraph marks. The above macro finds those paragraphs, add new and then remove it. which eventually removed the dotted line.

Can anybody explain this phenomena? what is the right ways to remove/replace those paragraphs. please download and see test file with error on page 7

Update: Even I tried with the following code but it did nothing (on MacOS Video). I think it is not finding the hidden paragraphs:

Sub HidNempty()

    Dim H As Range
    Set H = ActiveDocument.Range
    
    With H.Find
        
        .Text = "^p "
        .Replacement.Text = "^p"
        .Execute Replace:=wdReplaceAll
        
        .Text = " ^p"
        .Replacement.Text = "^p"
        .Execute Replace:=wdReplaceAll
        
        .Text = "^p ^p"
        .Replacement.Text = "^p^p"
        .Execute Replace:=wdReplaceAll
        
        .Text = "^p"
    Do While .Execute
        
        If H.Font.Hidden = True Then
            H.Font.Hidden = False
            If Len(Trim(H.Paragraphs(1).Range.Text)) = 1 Then
                H.Delete
            
            End If
        End If
    Loop
    End With
    
End Sub

Faulty Paragraph Marks



Modify daqapo::detect_value_range_violations to generate different result

I have the activitylog object below:

hospital<-structure(list(patient_visit_nr = c(510, 512, 510, 512, 512, 
                                              510, 517, 518, 518, 518, 519, 519, 520, 519, 521, 521, 519, 522, 
                                              522, 523, 524, 525, 526, 523, 527, 527, 527, 528, 528, 523), 
                         activity = c("registration", "Registration", "Triage", "Triage", 
                                      "Clinical exam", "Clinical exam", "Triage", "Registration", 
                                      "Registration", "Registration", "Registration", "Triage", 
                                      "Trage", "Clinical exam", "Triage", "Registration", "Treatment", 
                                      "Registration", "Triaga", "Registration", "Triage", "Triage", 
                                      "Triage", "Triage", "Registration", "Triage", "Clinical exam", 
                                      "Registration", "Triage", "Clinical exam"), originator = c("Clerk 9", 
                                                                                                 "Clerk 12", "Nurse 27", "Nurse 27", "Doctor 7", "Doctor 7", 
                                                                                                 "Nurse 17", "Clerk 12", "Clerk 6", "Clerk 9", "Clerk 12", 
                                                                                                 "Nurse 17", "Nurse 17", "Doctor 4", "Nurse 17", "Clerk 3", 
                                                                                                 "Nurse 17", "Clerk 3", "Nurse 5", "Clerk 9", "Nurse 5", "Nurse 5", 
                                                                                                 "Nurse 5", "Nurse 27", "Clerk 6", "Nurse 5", "Doctor 4", 
                                                                                                 "Nurse 6", "Nurse 6", "Doctor 4"), start = structure(c(1511173097, 
                                                                                                                                                        1511173994, 1511174048, 1511174652, 1511177232, 1511177701, 
                                                                                                                                                        1511264116, 1511264716, 1511264716, 1511264716, 1511265581, 
                                                                                                                                                        1511270783, 1511271796, 1511272354, 1511272924, 1511273120, 
                                                                                                                                                        1511275132, 1511277137, 1511277325, 1511282528, 1511283843, 
                                                                                                                                                        1511283853, 1511283855, 1511285190, 1511287330, 1511287331, 
                                                                                                                                                        1511287333, 1511287817, 1511288105, 1511288209), tzone = "UTC", class = c("POSIXct", 
                                                                                                                                                                                                                                  "POSIXt")), complete = structure(c(1511173206, 1511174220, 
                                                                                                                                                                                                                                                                     1511174508, 1511175017, 1511177637, 1511177769, 1511264340, 
                                                                                                                                                                                                                                                                     1511263336, 1511263336, 1511263336, 1511265952, 1511271138, 
                                                                                                                                                                                                                                                                     1511271540, 1511272954, 1511273169, 1511290800, 1511275761, 
                                                                                                                                                                                                                                                                     1511277499, 1511277484, 1511283119, 1511283965, 1511283968, 
                                                                                                                                                                                                                                                                     1511283970, 1511287261, 1511287447, 1511287448, 1511287450, 
                                                                                                                                                                                                                                                                     1511288104, 1511288412, 1511288528), tzone = "UTC", class = c("POSIXct", 
                                                                                                                                                                                                                                                                                                                                   "POSIXt")), triagecode = c(3, 3, 3, 3, 3, NA, 3, 4, 4, 4, 
                                                                                                                                                                                                                                                                                                                                                              4, 4, 5, 4, 2, 2, 4, 2, 2, 3, 3, 3, 4, 3, 2, 2, 2, 3, 3, 
                                                                                                                                                                                                                                                                                                                                                              3), specialization = c("TRAU", "URG", "TRAU", "URG", "URG", 
                                                                                                                                                                                                                                                                                                                                                                                     "URG", "URG", "PED", "PED", "PED", "PED", "PED", "URG", "PED", 
                                                                                                                                                                                                                                                                                                                                                                                     "URG", "URG", "PED", "URG", "URG", "URG", "URG", "URG", "URG", 
                                                                                                                                                                                                                                                                                                                                                                                     "URG", "URG", "URG", "URG", "TRAU", "TRAU", "URG"), .order = 1:30), row.names = c(NA, 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                       -30L), class = c("activitylog", "log", "tbl_df", "tbl", "data.frame"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                       ), case_id = "patient_visit_nr", activity_id = "activity", resource_id = "originator", timestamps = c("start", 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             "complete"))

and I want to modify the function daqapo::detect_value_range_violations in order to give me as final result the :

# Log of 0 events consisting of:
5 traces 
6 cases 
7 instances of 5 activities 
4 resources 

instead of the tibble that is generated with

hospital %>%
  detect_value_range_violations(triagecode = domain_numeric(from = 0, to = 5))

. How can i modify this function?



How to fix twitching/braking while scrolling website vertically up and down on iphone in safari

Tried many things, but still no results. Please help me to get rid of awful scroll effect which is twitching/braking while scrolling website vertically up and down. My website: https://evgeniyr1987.github.io/VisitCardPortfolio/, you can play that twitching/braking scroll effect on iphone and safari only, anywhere else works perfect! Here is the link to video for better understanding https://disk.yandex.ru/i/yck8jAbU7fBAtw.



algo - light illumination value mapping

Consider this board map : we have a board of m x n size, there are light bulbs with varying power installed in different cells on the map, 1 light bulb only per cell. if a bulb has power index of 10, then a cell whose shortest distance from the bulb is 4 cells away will receive 10 - 4 = 6 illumination index from the bulb.

for example, look at this initial stage

a light bulb with 7 illumination index is located in row 2 col 2 will illuminate cell in row 1 col 4 at 3 illumination index. if a cell receives illumination from multiple light bulbs, the one with highest illumination index wins.

for this board, the final state will look like this: final state

another example of a light bulb with illumination power of 10 placed at the center of the map example once the illumination power hits 0, no adjacent cell will be illuminated.

what I have in mind is to check each non-lightbulb cell on the board against each light bulb to determine the final illumination point on that cell. Is there a better way to solve this problem?



2022-12-26

getting error : HTTPerror: basic auth header is Invalid ,when sending files to ipfs

const projectId = process.env.PROJECTKEY
const projectSecret =process.env.SECRETKEY
const auth = 'Basic' + Buffer.from(projectId + ":" + projectSecret).toString('base64')


const client = IPFSHTTPClient({
  host:'infura-ipfs.io',
  port:5001,
  protocol:'https',
  headers:{
      authorization: auth
  }
  
  
})

i removed headers object and then got error- project id required



In RStudio, how to print tibble in quarto/rmarkdown chunk as in console?

When editing quarto/rmarkdown documents, I would like RStudio to display inline tibbles the same way as it does in the console, instead of the paginated default printing.

Instead of this:

Default printing of tibbles in RStudio IDE

I would much prefer the output from the console:

# A tibble: 150 × 5
   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
          <dbl>       <dbl>        <dbl>       <dbl> <fct>  
 1          5.1         3.5          1.4         0.2 setosa 
 2          4.9         3            1.4         0.2 setosa 
 3          4.7         3.2          1.3         0.2 setosa 
 4          4.6         3.1          1.5         0.2 setosa 
 5          5           3.6          1.4         0.2 setosa 
 6          5.4         3.9          1.7         0.4 setosa 
 7          4.6         3.4          1.4         0.3 setosa 
 8          5           3.4          1.5         0.2 setosa 
 9          4.4         2.9          1.4         0.2 setosa 
10          4.9         3.1          1.5         0.1 setosa 
# … with 140 more rows
# ℹ Use `print(n = ...)` to see more rows

I have tried setting #| results: asis and changing the df-print option in the yaml, but that only affects the rendered document. I could make RStudio show chunk output in the console instead, but I would prefer if i could keep it inline.



Untar specific files using lambda

I'm using a lambda function to untar files. The lambda is supposed to untar files and once it's done it moves the package to an archive folder.

Code below

def untar_file(zip_key,source_bucket,source_path,file):
 zip_obj = s3_resource.Object(bucket_name=source_bucket,key=zip_key)  
 buffer = BytesIO(zip_obj.get()["Body"].read())
 with tarfile.open(fileobj=buffer, mode=('r:gz')) as z:
     for filename in z.getmembers():
         s3_resource.meta.client.upload_fileobj(
         z.extractfile(filename),
         Bucket=source_bucket,
         Key=source_path+f'/{d1}/{filename}.csv'
         )
 copy_objects (zip_key,source_bucket,source_path,file)

I want to only untar specific files in the package. Can I specify which file to not untar? Just to avoid the lambda timeout



How to append to file before specific string in go?

I have a file that starts with this structure:

locals {
  MY_LIST = [
    "a",
    "b",
    "c",
    "d"
    //add more text before this
  ]
}

I want to add in the text "e" before the "//add more text before this" and "," after the "d" so it will be like this:

locals {
  MY_LIST = [
    "a",
    "b",
    "c",
    "d",
    "e"
    //add more text before this
  ]
}

How can I implement this dynamically so that I can add more strings to the file in the future?

Thanks



svelte rollup-plugin-css-only import not working

In a svelte project, I want to import some css files, and I cant make this plugin works : https://github.com/thgh/rollup-plugin-css-only

here is my config

project/rollup.config.js

/* other imports */
import css from 'rollup-plugin-css-only';

export default {
  plugins: [
    /* svelte here, */
    css({ output: 'public/build/extra.css' }),
    /*
      alternatives I tried :
    css(),
    css({ output: 'extra.css' }),
    css({ output: 'bundle.css' }),
    css({ output: 'public/build/bundle.css' }),
    */
  ]
};

I put intentionally the output in a separate file project/public/build/extra.css instead of the default project/public/build/bundle.css to see if the file will be created; and the file is never created

I searched with find . -type f -name "*extra.css" in the project root directory

the output file is included inside the project/public/index.html :

<link rel='stylesheet' href='/build/extra.css'>

and that gives me a log with error 404, which is normal if it was not created

I tried different ways to import :

project/src/component/exemple.css

inside the component :

project/src/component/exemple.svelte

<script>
  import './my_style.css';
</script>
<style>
  @import './my_style.css';
</style>
<style src='./my_style.css'>
</style>

the plugin is present in the package.json, and I did npm install --save-dev rollup-plugin-css-only



2022-12-25

Set the GUID value of VSTO AddIn

I don't understand how i can set the GUID value of a VSTO AddIn. In EventViewer i see Empty GUID: {00000000-0000-0000-0000-000000000000}.

enter image description here

I've tried using the Guid and ProgId attributes on the ThisAddIn class, but that doesn't help. Can you please tell me how to change the GUID.



A coredata computed property used to sort an array of object is not updated. Working when I go from view1 to view2, but not from view 3 to view2

I am still quite new at SwiftUI and I am having trouble to understand why the array that I have created in my model “GameSession”, which is sorted according to a computed variable defined in my second model “GamePlayer”, is not “always” correctly updated.

I have simplified my code to make it more readable, in order to maximize the chances of someone helping me!

Description of my code:

In my App, I have 2 entities

1.     GameSession :which has Attributes "date", "place", "nbplayer" + a relationship called "players" with " GamePlayer "

2.     GamePlayer: which has Attributes "name","scorelevel1","scorelevel2","scorelevel3" + a relationship with "GameSession"

the relationship is "one to many": One GameSession  can have many GamePlayer

 

And basically, I have 3 views:

View 1: Just one navigation link which brings you to View2

View2: Display a list of “Game” played (on which you can click to go to “view3”). For each one, I want to be able to display the date of the game, and the names of the players who played the game, sorted according to a variable “total_score”

View3: You can visualize the game on which you clicked in View2. And you see the name of the players who played the game, and you can modify the score of each player for each one of the 3 levels. And a variable “total_score” sums for each player the score of level 1 to 3

 My problem:

My issue, is that when I go from View3 to View2, the list of the players won’t be correctly sorted according to the “total_score” variable.

But If I go from View1 to View2, the list of the player is correctly sorted… 

I don’t understand what I am doing wrong. 

Here is my code:

My Model for GameSession is like that:. You will notice that I have created in my model a variable which is an array of “GamePlayer” sorted according to the computed variable “total_score” of the GamePlayer entity

import Foundation
import CoreData
 
 
extension GameSession {
 
    @nonobjc public class func fetchRequest() -> NSFetchRequest<GameSession> {
        return NSFetchRequest<GameSession>(entityName: "GameSession")
    }
 
    @NSManaged public var date: Date?
    @NSManaged public var nbplayer: Int32
    @NSManaged public var place: String?
    @NSManaged public var players: NSSet?
    @NSManaged public var photo: NSData?
 
    // pour gerer le fait que "date" ne doit pas etre vide
    public var wrappedDate: Date {
        date ?? Date()
    }
    public var wrappedNbplayer: Int32 {
        nbplayer
    }
    
    // pour gerer le fait que "lieu" ne doit pas etre vide
    public var wrappedPlace: String {
        place ?? "Endroit inconnu"    }
 
    
    // pour gerer le fait que "photo" ne doit pas etre vide
    public var wrappedPhoto: NSData {
        photo ?? NSData()
    }
    
    }
    //
    public var playersArrayRang: [GamePlayer] {
        let playersSet = players as? Set< GamePlayer > ?? []
 
        // On retourne un array sorted en fonction du score total
        return playersSet.sorted {
            $0.totalscore < $1.totalscore
        }
    }

And my model for “GamePlayer” is like that:

extension GamePlayer {
 
    @nonobjc public class func fetchRequest() -> NSFetchRequest< GamePlayer > {
        return NSFetchRequest< GamePlayer >(entityName: " GamePlayer ")
    }
 
    @NSManaged public var name: String?
    @NSManaged public var scorelevel1: Int64
    @NSManaged public var scorelevel2: Int64
    @NSManaged public var scorelevel3: Int64
    @NSManaged public var sessiongame: GameSession?
    
    public var wrappedName: String {
        name ?? "player unknown"
    }
 
    public var total_score: Int64 {
        scorelevel1 + scorelevel2 + scorelevel3
    }
 
}

View 1: GameUIView

struct GameUIView: View {
    var body: some View {
            NavigationLink(destination: GameListePartieUIView ()) {
                Text(" Mes parties ")
            }
    }
}

View 2: GameListePartieUIView

import SwiftUI
import Foundation
 
struct GameListePartieUIView: View {
    @Environment(\.managedObjectContext) var moc
    @FetchRequest(entity: GameSession.entity(), sortDescriptors: [
        NSSortDescriptor(keyPath: \GameSession.date, ascending: false)
    ]) var gamesessions: FetchedResults<GameSession>
    
    @State var showingAddPartie = false
    
    var body: some View {
        
//        VStack {
            List {
                ForEach(gamesessions, id: \.date) { session in
                    
                    HStack{
 
                        NavigationLink (destination: DetailPartieSelecUIView2(session: session)){
                            HStack{
                                Text(" \(session.wrappedDate, formatter: itemFormatter) ")
                                    .frame(width: 120, height: 50, alignment: .top)
                                    .font(.system(size: 12, weight: .light, design: .serif))
 
                                VStack(alignment: .leading){
                                    ForEach(Array(session.playersArrayRang.enumerated()), id: \.offset) { index, player in
                                        if index == 0 {
                                            Text("\(index+1) - \(player.wrappedName)")
                                                .frame(alignment: .leading)
                                                .lineLimit(1)
                                                .font(.system(size: 12, weight: .light, design: .serif))
//                                                .foregroundColor(Color(red: 0.246, green: 0.605, blue: 0))
                                                .foregroundColor(Color("Colorjb1"))
                                                .bold()
                                        } else {
                                            Text("\(index+1) - \(player.wrappedName)")
                                                .frame(alignment: .leading)
                                                .lineLimit(1)
                                                .font(.system(size: 12, weight: .light, design: .serif))
                                        }
 
                                    }
                                }
                                
                            }
                            
                        }
                        
                        
                        
                    }
                    
                }
                .onDelete(perform: deleteSessions)
                .padding(1)
            }
 
            .navigationBarItems(trailing: Button("Ajouter") {
                self.showingAddPartie.toggle()
            })
            .navigationBarTitle("Parties", displayMode: .inline)
            .sheet(isPresented: $showingAddPartie) {
                AddPartieRamiUIView().environment(\.managedObjectContext, self.moc)
            }
            .frame( maxWidth: .infinity)
            .edgesIgnoringSafeArea(.all)
            .listStyle(GroupedListStyle()) // or PlainListStyle()
            .padding(1)
    
    }
    
    
    // --------
    private func deleteSessions(at offsets: IndexSet) {
        for index in offsets {
            let session = ramisessions[index]
            moc.delete(session)
        }
        
        do {
            try moc.save()
        } catch {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            let nsError = error as NSError
            fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
        }
    }
    
}

View 3: DetailPartieSelecUIView2

struct DetailPartieSelecUIView2: View {
    @Environment(\.managedObjectContext) var moc
    
    @FetchRequest
    private var players: FetchedResults<GamePlayer>
    
    private var session_actuelle: GameSession
    
    init(session: GameSession) {
        let predicate = NSPredicate(format: "sessionramy = %@", session)
        let sortDescriptors = [SortDescriptor(\GamePlayer.name)] // need something to sort by.
        _players = FetchRequest(sortDescriptors: sortDescriptors, predicate: predicate)
        session_actuelle = session
    }
    
    let formatter: NumberFormatter = {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        return formatter
    }()
 
    
    var body: some View {
        
        VStack {
            ScrollView(.vertical){
 
                Text("\(session_actuelle.wrappedLieu) - \(session_actuelle.wrappedDate, formatter: itemFormatter)")
                
                ScrollView([.horizontal, .vertical]) {
                    HStack(alignment:.center){
                        // 1er element de mon HStack
                        VStack {
                                Text(" ")
                                Divider()
                                Text("Level 1")
                                Text("Level 2")
                                Text("Level 3")
                                Divider()
                                Text("Total")
                            }
                        // 2eme element de mon HStack
                        ForEach(players, id: \.wrappedName) { player in
                            PlayerView(player: player)
                        }
                    } // HStack
                } //scrollView
 
                // bouton pour sauvegarder les scores de la partie
                Button("Save scores") {
                        do {
                            try self.moc.save()
                        } catch {
                            print("Whoops! \(error.localizedDescription)")
                        }
                    }
 
            }
        }
    }
}
 
struct PlayerView: View {
    @ObservedObject var player:GamePlayer
 
    @Environment(\.managedObjectContext) var moc
    
    @State private var numberFormatter: NumberFormatter = {
        var nf = NumberFormatter()
        nf.numberStyle = .decimal
        return nf
    }()
    
    var body: some View {
        
        VStack {
            
 
                Text(player.wrappedName)
                Divider()
                TextField("Score", value: $player.scorelevel1, formatter:NumberFormatter())
                TextField("Score", value: $player.scorelevel2, formatter:NumberFormatter())
                TextField("Score", value: $player.scorelevel3, formatter:NumberFormatter())
                Divider()
                Text(String(player.scoretotal))
                
            }
    }
}
 
extension Binding {
    func toUnwrapped<T>(defaultValue: T) -> Binding<T> where Value == Optional<T>  {
        Binding<T>(get: { self.wrappedValue ?? defaultValue }, set: { self.wrappedValue = $0 })
    }
}
 

When I am in my “View3” and I change values in the TextField (of PlayerView), player.scoretotal is updated accordingly.

Then I click on my button "Save scores", in order to save my “moc” (Core Data)

But when I click on “back” (on the top left corner of the view) and that I go back to the previous view (View2), the right part of my list, where I am supposed to sort players name according to their total_score, is not updated…

What is weird, is that, if I go “back” to my “View1”, and that I click on the navigation link which open my “View2” (DetailPartieSelecUIView2), Then the names of the players are sorted correctly…

Thanks a lot for reading my long post. Hopefully somebody can help me. Best regards!

I tried everything...



Changes are not reflecting in azure app service after deploying via azure devops pipeline

I have a CI/CD pipeline in the Azure DevOps pipeline that deploys the app into the Azure App Service. Both the build and release pipelines are executing without any errors. Before some days, the deployed changes were working fine but now the changes are not reflecting even though the pipeline is executing without any errors.

Release pipeline definition: https://prnt.sc/UE1039_bI6Tz

While analyzing the release pipeline, in the 'Deploy azure app service' task it shows, Total changes: 0 (0 added, 0 deleted, 0 updated, 0 parameters changed

build pipeline debug log file: https://drive.google.com/drive/folders/1ReX_rCuqANfvmFrfHb7es-CiU7GxDEPf?usp=share_link

release pipeline debug log file: https://drive.google.com/file/d/1xrokn_itGWMKqcKRMIRf-OigRhJOHvVp/view?usp=share_link

I checked the artifact created in build pipeline and the changes are there in artifact. But in the release pipeline the changes are not refelected. I checked in the kudu console and the changes are not there also.

When I manually deploy the changes to the app services, they are successfully deployed and the changes are reflected. I don't know what happens behind the scene.

Can anyone please guide me on this? Thanks!

I need the changes to be reflected in the azure app service deployed via the azure DevOps release pipeline.



How to match more than 2 side by side

I'm currently using python and having trouble finding a code. I have 2 data frames that I would like to match more than 2 numbers that match side by side. For example, I would like to lookup the numbers in df1 and find more than 2 numbers match side by side in df2.

import pandas as pd 
cols = ['Num1','Num2','Num3','Num4','Num5','Num6']
df1 = pd.DataFrame([[2,4,6,8,9,10]], columns=cols)

df2 = pd.DataFrame([[1,1,2,4,5,6,8],
           [2,5,6,20,22,23,34],
           [3,8,12,13,34,45,46],
           [4,9,10,14,29,32,33],
           [5,1,22,13,23,33,35],
           [6,1,6,7,8,9,10],
           [7,0,2,3,5,6,8]], 
           columns = ['Id','Num1','Num2','Num3','Num4','Num5','Num6'])

I would like my results to be something like this.

results = pd.DataFrame([[6,1,6,7,8,9,10]],             
       columns = ['Id', 'Num1','Num2','Num3','Num4','Num5','Num6']) 

You can see Id 6 or index 6 has 8,9,10. More than 2 number match side by side.



Looking for a self contained simple c# example of FFmpeg AutoGen encoding

I'm unable to get the FFmpeg.AutoGen.Example code to work in my own project. The example has the FFmpeg.AutoGen.Abstractions project as a dependency. I can't figure out how to replicate or reference it in my project. The only other example that I can find has data elements that Visual Studio isn't able to resolve.

The FFmpeg.AutoGen.Bindings.DynamicallyLoaded project is referenced in the same way but I was able to compile it and add the DLL as an assembly in my project. When I do the same for the Abstractions class, the data classes defined in it weren't equivalent to the FFmpeg.AutoGen data classes. It's like I need a reference to Abstractions in FFmpeg.AutoGen but it's not there.

enter image description here



How to create a automatic pop up in wordpress either through plugin or by coding

I have developed a website on wordpress and the requirement for website backend admin panel is that the order details automatically get poped up when any new order is recieved on website without clicking any button.

I am not able to change the source file of the plugin or theme. If someone can help me out in adding that code to the plugin or theme.



2022-12-24

How to get host where problem appears Zabbix-api

I'm trying to make a script on Python, which works with zabbix-api.

For example: Trigger worked, problem appears and then I make an "action trigger", which will work on that host, where problem appeared. For the script, I need to get host (and host id), where problem appeared and then resolve the problem. But I don't know how to get only this host. Please, could you help me with this or maybe give me some advice, what am I doing wrong?

I tried something like:

my_host = zabbix_log.host.get(limit=1, output=["hostid", "name", "host"])[0]

Of course, it works, but I understand, that this is only give to me some random host, and not the host where problem appeared



Boost static linking to custom library somehow broken (Windows)

I am trying to build a Library (MyLib) that has a static dependency to boost. However, when I am trying link MyLib to an Application I will get linking erorrs saying that boost functions cannot be found.

I did used the pointer to implementation idiom. Conan installed the static lib of boost (I checked that). The plattform is windows.

Does anyone has an idea what I am doing wrong?

Here is the CMakeLists.txt

cmake_minimum_required(VERSION 3.24)

set(TARGET_NAME MyLib)
project(${TARGET_NAME}Project)

include(${CMAKE_CURRENT_LIST_DIR}/build/conanbuildinfo.cmake)
conan_basic_setup()


set(
    SRC_FILES
    src/FileA.cpp
    src/FileB.cpp
    src/FileC.cpp
)

add_library(${TARGET_NAME} ${SRC_FILES})
target_include_directories(
    ${TARGET_NAME} 
    PUBLIC ${CMAKE_CURRENT_LIST_DIR}/include/public 
    PRIVATE ${CMAKE_CURRENT_LIST_DIR}/include/private
)

target_link_libraries(${TARGET_NAME} PRIVATE ${CONAN_LIBS_STATIC})
set_property(TARGET ${TARGET_NAME} PROPERTY CXX_STANDARD 17)

install(TARGETS ${TARGET_NAME} DESTINATION lib)

This is the erorr I am getting:

Severity    Code    Description Project File    Line    Suppression State
Error   LNK2001 unresolved external symbol "public: class boost::log::v2s_mt_nt6::attribute_value_set::const_iterator __cdecl boost::log::v2s_mt_nt6::attribute_value_set::end(void)const " (?end@attribute_value_set@v2s_mt_nt6@log@boost@@QEBA?AVconst_iterator@1234@XZ)  Main    C:\dev\TestProjects\VSLog\Main\CppLogLib.lib(ConsoleLogWrapper.obj) 1   

Many thanks in advance.

I tried with CMake setting like set(Boost_USE_STATIC_LIBS ON) or set_target_properties(${TARGET_NAME} PROPERTIES LINK_FLAGS "OPT:NOREF") but it did not help.

I also try to build MyLib using sln (and Boost downloaded from boost.org) and here I also get a linking error:

Error LNK1104 cannot open file 'libboost_log-vc143-mt-gd-x64-1_81.lib'



How does firebase authentication work with ionic and capacitor?

When the app is launching for the sign in page, an error is occurring that relates to the authorized domains: Cross-origin redirection to http://developers.google.com/ denied by Cross-Origin Resource Sharing policy: Origin capacitor://localhost is not allowed by Access-Control-Allow-Origin. Status code: 301

When I try to add capacitor://localhost to the list of authorized domains, it throws the error A valid domain name is required (e.g. 'myapp.com')

My authentication code both has a listener:

  useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, async (userInfo) => {
      setUser(userInfo);
      if (userInfo === null) {
        localStorage.clear();
        history.push("/login");
      } else {
        const token = await userInfo.getIdToken(true);
        history.push("/home");
        localStorage.setItem("AuthToken", `Bearer ${token}`);
      }
    });
    return unsubscribe;
  }, [user, history]);

and the sign in function:


export const signIn = async (email, password) => {
  try {
    await setPersistence(auth, browserLocalPersistence);
    const userCredential = await signInWithEmailAndPassword(
      auth,
      email,
      password
    );

    const user = userCredential.user;
    const token = await user.getIdToken(true);
    localStorage.setItem("AuthToken", `Bearer ${token}`);
    return { user, token };
  } catch (error) {
    return { error: error.message };
  }
};

I have seen some answers that might suggest it has to do with the Firebase Auth SDK having issues with capacitor because it is meant for a web app instead of mobile apps. However, there has not been very clear answers as to how I can confirm if that is the problem or how to solve it.



How to use React-datepicker with custom data

I am trying to make a custom react-datepicker but my code is not working correctly.

const [filterDateFrom, setFilterDateFrom] = useState("");
const [filterDateTo, setFilterDateTo] = useState("");
const [startDate, endDate] = filterDateFrom && filterDateTo;

then I have a function to pull the date and my return is something like:

<div>
  <DatePicker
   filterDateFrom={true}
   filterDateTo={true}
   startDate={startDate}
   endDate={endDate}
   onChange={(update) => {
   setFilterDateFrom(update) && setFilterDateTo(update)
   }}
   withPortal
   />
 </div>

But when I select the dates the code breaks.

The DatePicker on the official documentation looks like this:

<DatePicker
      selectsRange={true}
      startDate={startDate}
      endDate={endDate}
      onChange={(update) => {
        setDateRange(update);
      }}
    />

Any ideas?

Here is a snippet from my JSON file:

[
  {
    "id": 1,
    "Period From": "2021-01-31T23:00:00.000Z",
    "Period To": "2021-02-27T23:00:00.000Z",
  }
]

Update on my Code:

const [filterDateFrom, setFilterDateFrom] = useState(new Date());
const [filterDateTo, setFilterDateTo] = useState(null);

  const onChange = (dates) => {
    console.log(dates);
    const [start, end] = dates;
    setFilterDateFrom(start);
    setFilterDateTo(end);
  };

And then Im applying a filter that looks like this:

const displaySongs = songs
.filter((song) => {
keepSong &&=
        filterDateFrom === "" || filterDateTo === "" ||
        song["Period From"]?.toLowerCase().includes(filterDateFrom.toLowerCase() || song["Period To"]?.toLowerCase().includes(filterDateTo.toLowerCase()));

      return keepSong;
    })
    .map((song) => {
      return (
        <tr className="font-medium bg-white border-b dark:bg-gray-800 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-600">

          ... I'm displaying more data here

          <td className="py-2 px-4 text-left">{song["Track Title"]}</td>
          ... and here.
        </tr>
      );
    });

return (
    <div className="flex-1 px-10">
      <div className="flex gap-4">
        <div className="flex sticky top-0 justify-between items-center my-10 gap-4 shadow-md rounded-md p-6 bg-slate-900">
      <div>
      <DatePicker
        selected={filterDateFrom}
        onChange={onChange}
        startDate={filterDateFrom}
        endDate={filterDateTo}
        selectsRange

      />
      </div>

      <table className="w-full text-sm text-left text-gray-500 dark:text-gray-400 shadow-md rounded">
        <thead className="text-gray-700 uppercase bg-slate-50 dark:bg-gray-700 dark:text-gray-400">
          <tr>
            <th className="py-2 px-4 text-left">Track Title</th>
          </tr>
        </thead>
        <tbody>{displaySongs}</tbody>
      </table>
      <div>

Im getting this error in my console:

react-dom.development.js:26923 Uncaught TypeError: filterDateFrom.toLowerCase is not a function


WÄ°NDOWS FORM c# How to detect empty space in datagridview and warn the screen if it is empty? [closed]

  • I want only 3 of the columns in my table in Datagridview1 not to be empty. I want it to warn the screen when there is an empty field.

  • I tried to make a mandatory field to be filled in the datagridview1 table

  • When I add other data to the data I pull from sql in Datagridview, I want it to warn the screen to be filled if there should be no empty space.

  • As you can see in the photo below, only those places should not be empty, and when I press save, it should detect when there is an empty space and give a warning to the screen.

  • give a warning if there is free space



2022-12-23

Converting list of string into dataframe row

I have the following continent to country

pd.DataFrame({'asia':[['china','india','australia']],
              'europe':[['spain','uk','russia','france','germany']],
              'americas':[['canada','usa','mexico']]
            }).transpose()

How do I convert into

asia | china
asia | india
asia | australia
europe | spain
europe | uk

etc. .



Json contains with exclusion or wildcard

Is there a way to either wildcard or exclude fields in a json_contains statement (postgres w/ sqlalchemy)?

For example, lets say one of the rows of my database has a field called MyField which has a typical json value of ...

MyField : {Store: "HomeDepot", Location: "New York"}

Now, I am doing a json contains on that with a larger json variable called larger_json...

larger_json : {Store: "HomeDepot", Location: "New York", Customer: "Bob" ... }

In sqlalchemy, I could use a MyTable.MyField.comparator.contained_by(larger_json) and in this case, that would work fine. But what if, for example, I later removed Location as a field in my variable... so I still have the value in my database, but it no longer exists in larger_json:

MyField : {Store: "HomeDepot", Location: "New York"}
larger_json : {Store: "HomeDepot", Customer: "Bob" ... }

Assume that I know when this happens, i.e. I know that the database has Location but the larger_json does not. Is there a way for me to either wildcard Location, i.e. something like this...

{Store: "HomeDepot", Location: "*", Customer: "Bob" ... }

or to exclude it from the json value? Something like this?

MyTable.MyField.exclude_fields().comparator.contained_by(larger_json)

Or is there another recommended approach for dealing with this?



How to convert two's complement to an int - using C?

I'm trying to read a register from an INA260 using a Pico microcontroller. My program is in C. The register I'm having trouble with contains the value of the electrical current measured by the INA260. Since the INA260 accommodates measurement of current flowing in either direction, the mfr decided to cast the two bytes of measurement data in two's complement. This allows for a "negative" current - meaning only that the current is flowing in one direction instead of the other. I can appreciate this is a clever solution from a hardware perspective, but from the software perspective, I am very fuzzy on two's complement.

In an effort to help frame my question & give it some context, here's how I read & process the INA260's measured electrical current in the designated register. This code may not be elegant, but it gives the correct answer:

    uint8_t rcvdata[2];

/*  Read the Current Register (01h); INA260_MILAMP_REG _u(0x01)  */

    reg = INA260_MILAMP_REG;
    i2c_write_blocking (i2c_default, ADDR, &reg, 1, true);
    i2c_read_blocking(i2c_default, ADDR, rcvdata, 2, false);
    int milliamps = rcvdata[1] | rcvdata[0] << 8;
    printf("\ninteger value in register: %d milliamps", milliamps);
    printf("\nmeasure current by INA260: %.*f amps\n", 2, milliamps*1.25/1000);

In summary:

  • define the data register location (reg) & send that to the INA260 at its bus address
  • read 2 bytes (MSB first) into the rcvdata array
  • convert the 2 byte unsigned data to an integer
  • convert the result to amps (from milliamps; 1.25mA is one unit), and print
  • Register bytes are sent via I2C interface, MSB first.

Following is the output from this code:

integer value in register 0x01: 39 
measured current at IN+ pin: 0.05 amps (i.e. 47.5 mA)

The code above yielded the correct answer in this case. In other words, as I have the INA260 wired, the current flows in the direction designated as positive by the manufacturer. As I understand it, the two's complement format is exactly the same as unsigned data when the value is positive, and so I "got lucky". However, there will be other situations when the INA260 is wired in such a way that the current is considered "negative", and I'm in a fog as to how to deal with two's complement when the value is negative.

Now then, at last, my questions are these:

  1. What changes are needed to the code listed above so that it can recover the negative integer value? i.e. what do I need to do instead of int milliamps = rcvdata[1] | rcvdata[0] << 8; to get the negative value?

  2. As I understand it, two's complement format is not covered by a standard, nor is it a data type in C. If that's true, how one can know if a block of data is cast as two's complement?