Is there a Python equivalent of the C# null-coalescing operator?

Is there a Python equivalent of the C# null-coalescing operator?

other = s or some default value

Ok, it must be clarified how the or operator works. It is a boolean operator, so it works in a boolean context. If the values are not boolean, they are converted to boolean for the purposes of the operator.

Note that the or operator does not return only True or False. Instead, it returns the first operand if the first operand evaluates to true, and it returns the second operand if the first operand evaluates to false.

In this case, the expression x or y returns x if it is True or evaluates to true when converted to boolean. Otherwise, it returns y. For most cases, this will serve for the very same purpose of C♯s null-coalescing operator, but keep in mind:

42    or something    # returns 42
0     or something    # returns something
None  or something    # returns something
False or something    # returns something
    or something    # returns something

If you use your variable s to hold something that is either a reference to the instance of a class or None (as long as your class does not define members __nonzero__() and __len__()), it is secure to use the same semantics as the null-coalescing operator.

In fact, it may even be useful to have this side-effect of Python. Since you know what values evaluates to false, you can use this to trigger the default value without using None specifically (an error object, for example).

In some languages this behavior is referred to as the Elvis operator.

Strictly,

other = s if s is not None else default value

Otherwise, s = False will become default value, which may not be what was intended.

If you want to make this shorter, try:

def notNone(s,d):
    if s is None:
        return d
    else:
        return s

other = notNone(s, default value)

Is there a Python equivalent of the C# null-coalescing operator?

Heres a function that will return the first argument that isnt None:

def coalesce(*arg):
  return reduce(lambda x, y: x if x is not None else y, arg)

# Prints banana
print coalesce(None, banana, phone, None)

reduce() might needlessly iterate over all the arguments even if the first argument is not None, so you can also use this version:

def coalesce(*arg):
  for el in arg:
    if el is not None:
      return el
  return None

Related Posts

What is sys.maxint in Python 3?

What is sys.maxint in Python 3?

The sys.maxint constant was removed, since there is no longer a limit
to the value of integers. However, sys.maxsize can be used as an
integer larger than any practical list or string index. It conforms to
the implementation’s “natural” integer size and is typically the same
as sys.maxint in previous releases on the same platform (assuming the
same build options).

http://docs.python.org/3.1/whatsnew/3.0.html#integers

As pointed out by others, Python 3s int does not have a maximum size, but if you just need something thats guaranteed to be higher than any other int value, then you can use the float value for Infinity, which you can get with float(inf).

Note: as per elys comment, this may impact the efficiency of your code, so it may not be the best solution.

What is sys.maxint in Python 3?

If you are looking for a number that is bigger than all others:

Method 1:

float(inf)

Method 2:

import sys
max = sys.maxsize

If you are looking for a number that is smaller than all others:

Method 1:

float(-inf)

Method 2:

import sys
min = -sys.maxsize - 1

Method 1 works in both Python2 and Python3. Method 2 works in Python3. I have not tried Method 2 in Python2.

Related Posts

Windows 10 – Task Scheduler – Not running (0x41303)

Windows 10 – Task Scheduler – Not running (0x41303)

I had this problem as well (Windows Server 2019), with error 0x41303 and Last Run Time set to 30/11/1999.

When I changed the start time to a future time instead of past (i.e. 2 minutes from current time), the scheduled task ran successfully (result: 0x0) and repeated just fine per the trigger.

Task Scheduler 0x41303: Task has not yet run.

The main reason for this is if the schedulers first run is set in the past or simply hasnt run yet. To fix:

  • Try running it manually
    or
  • Set the next trigger in the near future.

    The last run result should update indicating it ran but if it still doesnt run, check the task conditions.

    A full list of task scheduler return codes

Windows 10 – Task Scheduler – Not running (0x41303)

Got the same error code when scheduling a python script, fixed it by changing Conditions > Network to Any connection or disabling it entirely.

Related Posts

c# – wpf eventsetter handler binding in style

c# – wpf eventsetter handler binding in style

Right now you are binding the MouseLeftButtonDown Event to TextBlock.TextBlockMouseLeftButtonDownCommand. TextBlockMouseLeftButtonDownCommand is not a valid property for a TextBlock, nor does it sound like its an Event Handler.

I use the AttachedCommandBehavior all the time in styles for hooking up a Command to an Event. The syntax usually looks like this (note the DataContextin the Command Binding):

<Style x_Key=ItemTextBlockEventSetterStyle TargetType={x:Type TextBlock}>
    <Setter Property=local:CommandBehavior.Event Value=MouseLeftButtonDown />
    <Setter Property=local:CommandBehavior.Command
            Value={Binding DataContext.TextBlockMouseLeftButtonDownCommand, 
                            RelativeSource={RelativeSource Self}} />
</Style>

The alternative is to hook the EventSetter up to an event in the code-behind, and process the command from there:

<Style x_Key=ItemTextBlockEventSetterStyle TargetType={x:Type TextBlock}>
    <EventSetter Event=MouseLeftButtonDown 
                 Handler=TextBlockMouseLeftButtonDown/>
</Style>

Event handler in code behind…

void TextBlockMouseLeftButtonDown(object sender, MouseEventArgs e)
{
    var tb = sender as TextBlock;
    if (tb != null)
    {
        MyViewModel vm = tb.DataContext as MyViewModel;

        if (vm != null && TextBlockMouseLeftButtonDownCommand != null
            && TextBlockMouseLeftButtonDownCommand.CanExecute(null))
        {
            vm.TextBlockMouseLeftButtonDownCommand.Execute(null)
        }
    }
}

As you are using MVVM, I suggest you Galasoft MVVM Light Toolkit EventToCommand

c# – wpf eventsetter handler binding in style

My answer on this question does the trick without any external tool kits/libraries. However, it does not use RelativeSource, and it is not 100% MVVM. It requires one line of code in a code-behind event handler.

Related Posts

iOS 3D Touch API using Javascript for Web App

iOS 3D Touch API using Javascript for Web App

Safari 9 supports it on desktop. See Responding to Force Touch Events from JavaScript in Apples WebKit DOM Programming Topics.

I cant find any documentation on using it from Safari 9 on iOS, though.

You CAN use force touch on BOTH iPhone and Mac. You can use the the JS library Pressure.js. It makes it really easy to get Force and 3D Touch values on iOS and OSX if you have an iPhone 6s or new Macbook with the new Force Touch trackpads. There is currently only support in Safari but hopefully more browsers will have support soon.

The syntax is really simple too, here is an example:

Pressure.set(#element, {
  start: function(){
    // this is called on force start
  },
  end: function(){
    // this is called on force end
  },
  startDeepPress: function(){
    // this is called on force click / deep press, aka once the force is greater than 0.5
  },
  endDeepPress: function(){
    // this is called when the force click / deep press end
  },
  change: function(force, event){
    // this is called every time there is a change in pressure
    // here the force variable passed in container the current pressure force
  },
  unsupported: function(){
    // this is called once there is a touch on the element and the device or browser does not support Force or 3D touch
  }
});

iOS 3D Touch API using Javascript for Web App

Related Posts

azure active directory – Powershell Get-AzureADAuditSignInLogs Limits

azure active directory – Powershell Get-AzureADAuditSignInLogs Limits

I tested in my environment with lasted AzureADPreview module and getting same error as you are getting.

With the latest module Ive found this error appears only for certain log entries. For example, filter on a specific user UPN.

$signons = Get-AzureADAuditSignInLogs -Filter createdDateTime ge $filterDate and userPrincipalName eq $user.UserPrincipalName

Tried with older module version like 2.0.2.85, 2.0.2.89, 2.0.2.105 but getting the same error.

Note : These PowerShell cmdlets currently only work with the Azure AD Preview Module. Please note that the preview module is not suggested for production use.

Please check same it has mentioned over here

I have tried on specific user filter on userDisplayName for that it has working.

 $signons = Get-AzureADAuditSignInLogs -Filter createdDateTime gt 2021-10-18 and userDisplayName eq MOD Administrator |
               Select-Object Id,CreatedDateTime,UserId,AppId,AppDisplayName,IpAddress,ClientAppUsed,IsInteractive,TokenIssuerType,ProcessingTimeInMilliseconds
                  
Write-Output (--- All Okay ---)
    $signons | Export-Csv -Path C:AzureADAADSignOn.txt -NoTypeInformation -Append 

enter

Output–
enter

But Same is not running for UPN and getting error.

enter

Loop is not completing for all the users.

enter

Many of the users has reported the same issue went through this github discussion as well but didn’t get the proper solution would suggest you to please reach out to MS support team.

I got the same error from looping through a set of users in my environment. Now ive not tested this extensively, but adding a delay to each request seems to bypass this error in my case at least.

I simply added Start-Sleep -Milliseconds 500 to the end of each request. Granted my user-base wasnt that large so this might add significant time to your loop, but the errors did not occur afterwards.

Edit: Running a try/catch statement and only delaying upon error i found to be a faster way than a consistent delay.

    try {
        $UPN = $entry.Trim()
        Get-AzureADAuditSignInLogs -Filter UserPrincipalName eq $UPN | select UserPrincipalName,CreatedDateTime -Last 1 | Out-File -FilePath $login_file -Append
    }
    catch {
        $UPN = $entry.Trim()
        Start-Sleep -Seconds 20
        Get-AzureADAuditSignInLogs -Filter UserPrincipalName eq $UPN | select UserPrincipalName,CreatedDateTime -Last 1 | Out-File -FilePath $login_file -Append
    }

azure active directory – Powershell Get-AzureADAuditSignInLogs Limits

Related Posts

python 3.x – sqlalchemy.exc.ArgumentError: Could not parse rfc1738 URL from string

python 3.x – sqlalchemy.exc.ArgumentError: Could not parse rfc1738 URL from string

You are not using a valid URL in the connection string.

Review the documentation on how the MySQL connection URLs need to be structured: http://docs.sqlalchemy.org/en/latest/dialects/mysql.html.

Depending on the MySQL driver that you use the connection URL is different. For example, if you use pymysql, your URL should be:

mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>]

id forget the port number to enter the port, this is the URL connection string:

`SQLALCHEMY_DATABASE_URI = mysql://dt_admin:dt2016@localhost:3308/dreamteam_db

it work now, thanks

python 3.x – sqlalchemy.exc.ArgumentError: Could not parse rfc1738 URL from string

URL in the connection string is not valid.

you can check the documentation on how the MySQL connection URLs need to be structured here : http://docs.sqlalchemy.org/en/latest/dialects/mysql.html.

Example syntax for postgresql with psycopg2 driver it look like this :-

sql_alchemy_conn = postgresql+psycopg2://ubuntu@localhost:5432/airflow

Related Posts

visibility – How to hide a turtle icon/pointer in Python

visibility – How to hide a turtle icon/pointer in Python

The documentation has a section on Visibility:

turtle.hideturtle()
turtle.ht()
Make the turtle invisible. It’s a good idea to do this while you’re in the middle of doing some complex drawing, because hiding the turtle speeds up the drawing observably.

>>> turtle.hideturtle()

Also, you can un-hide the turtle:

turtle.showturtle()
turtle.st()
Make the turtle visible.

>>> turtle.showturtle()

You can also query its visibilty:

turtle.isvisible()
Return True if the Turtle is shown, False if it’s hidden.

>>> turtle.hideturtle()
>>> turtle.isvisible()
False
>>> turtle.showturtle()
>>> turtle.isvisible()
True

One more practical method that the other answer failed to address is to set the visible keyword argument to False when defining the Turtle object:

import turtle

my_turtle = turtle.Turtle(visible=False)

Of course, that is for when you want the Turtle to be invisible from the very beginning of the program.

When you define a Turtle object without setting visible to False, there will always be a lightning short moment where the turtle is still visible:


import turtle

my_turtle = turtle.Turtle()
# The Turtle may be visible before the program reaches the line under, depending on the speed of your computer 
my_turtle.hideturtle()

With the visible keyword argument set to False, you can always call my_turtle.showturtle() and my_turtle.hideturtle() in your code where ever the Turtle needs to be visible and hidden again.


Here are all the default turtle settings that you can customize (the settings of interest here are the ones commented with the # RawTurtle):

_CFG = {width : 0.5,               # Screen
        height : 0.75,
        canvwidth : 400,
        canvheight: 300,
        leftright: None,
        topbottom: None,
        mode: standard,          # TurtleScreen
        colormode: 1.0,
        delay: 10,
        undobuffersize: 1000,      # RawTurtle
        shape: classic,
        pencolor : black,
        fillcolor : black,
        resizemode : noresize,
        visible : True,
        language: english,        # docstrings
        exampleturtle: turtle,
        examplescreen: screen,
        title: Python Turtle Graphics,
        using_IDLE: False
       }

Update: I just noticed that cdlanes comment on the other answer pointed out this method, but comments are temporary.

visibility – How to hide a turtle icon/pointer in Python

Related Posts

Python 3.5.2 , openpyxl v 2.4.1 ,get_highest_row() , AttributeError

Python 3.5.2 , openpyxl v 2.4.1 ,get_highest_row() , AttributeError

Check out enigmas answer

wb = load_workbook(path, use_iterators=True)
sheet = wb.worksheets[0]

row_count = sheet.max_row
column_count = sheet.max_column

I think that method is depreciated,
In the newer version of openpyxl library
Visit https://pypi.org/project/openpyxl/
you can use this method to get the Row Count and Column count

#to get the row count
sheet.max_row
#to get the column count
sheet.max_column

Python 3.5.2 , openpyxl v 2.4.1 ,get_highest_row() , AttributeError

Related Posts

python – How to convert _io.TextIOWrapper to string?

python – How to convert _io.TextIOWrapper to string?

You need to use the output of f.read().

string = f.read()

I think your confusion is that f will be turned into a string just by calling its method .read(), but thats not the case. I dont think its even possible for builtins to do that.

For reference, _io.TextIOWrapper is the class of an open text file. See the documentation for io.TextIOWrapper.


By the way, best practice is to use a with-statement for opening files:

with open(document.txt, r, encoding=utf-8-sig) as f:
    string = f.read()

Its not a super elegant solution but it works for me

def extractPath(innie):
    iggy = str(innie)

    getridofme =<_io.TextIOWrapper name=
    getridofmetoo = mode=r encoding=UTF-8>

    iggy = iggy.replace(getridofme, )
    iggy = iggy.replace(getridofmetoo, )
    #iggy.trim()

    print(iggy)

    return iggy

python – How to convert _io.TextIOWrapper to string?

Related Posts