kandi background
Explore Kits

pendulum | Python datetimes made easy | Date Time Utils library

 by   sdispater Python Version: 2.1.2 License: MIT

 by   sdispater Python Version: 2.1.2 License: MIT

Download this library from

kandi X-RAY | pendulum Summary

pendulum is a Python library typically used in Utilities, Date Time Utils applications. pendulum has no bugs, it has no vulnerabilities, it has a Permissive License and it has high support. However pendulum build file is not available. You can download it from GitHub.
Python datetimes made easy
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • pendulum has a highly active ecosystem.
  • It has 4422 star(s) with 250 fork(s). There are 60 watchers for this library.
  • It had no major release in the last 12 months.
  • There are 161 open issues and 222 have been closed. On average issues are closed in 130 days. There are 34 open pull requests and 0 closed requests.
  • It has a negative sentiment in the developer community.
  • The latest version of pendulum is 2.1.2
pendulum Support
Best in #Date Time Utils
Average in #Date Time Utils
pendulum Support
Best in #Date Time Utils
Average in #Date Time Utils

quality kandi Quality

  • pendulum has 0 bugs and 0 code smells.
pendulum Quality
Best in #Date Time Utils
Average in #Date Time Utils
pendulum Quality
Best in #Date Time Utils
Average in #Date Time Utils

securitySecurity

  • pendulum has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • pendulum code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
pendulum Security
Best in #Date Time Utils
Average in #Date Time Utils
pendulum Security
Best in #Date Time Utils
Average in #Date Time Utils

license License

  • pendulum is licensed under the MIT License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
pendulum License
Best in #Date Time Utils
Average in #Date Time Utils
pendulum License
Best in #Date Time Utils
Average in #Date Time Utils

buildReuse

  • pendulum releases are available to install and integrate.
  • pendulum has no build file. You will be need to create the build yourself to build the component from source.
  • pendulum saves you 7589 person hours of effort in developing the same functionality from scratch.
  • It has 15658 lines of code, 1566 functions and 186 files.
  • It has high code complexity. Code complexity directly impacts maintainability of the code.
pendulum Reuse
Best in #Date Time Utils
Average in #Date Time Utils
pendulum Reuse
Best in #Date Time Utils
Average in #Date Time Utils
Top functions reviewed by kandi - BETA

kandi has reviewed pendulum and discovered the below as its top functions. This is intended to give you an instant insight into pendulum implemented functionality, and help decide if they suit your requirements.

  • Parse ISO 8601 string .
  • Computes the precise difference between two dates .
  • Parse an ISO8601 duration string .
  • Check the parsed data .
  • Parse the given text .
  • Returns the unix timezone for the given environment .
  • Create a new instance of this class .
  • Add this duration to another .
  • Extend the transitions .
  • Returns the windows timezone information .

pendulum Key Features

Python datetimes made easy

Matplotlib plot of ODE solution is not tangential to RHS vector field

copy iconCopydownload iconDownload
# Plotting
fig,ax=plt.subplots(figsize=(8,8))
ax.plot(ode_sol_y[:,0], ode_sol_y[:,1])
plt.quiver(ode_sol_y[::draw_arrow_every_nth, 0], ode_sol_y[::draw_arrow_every_nth, 1], vector_field_at_ode_sol_y[:,0], vector_field_at_ode_sol_y[:,1])
plt.quiver(alpha_2dgrid, alpha_dot_2dgrid,alpha_dt, alpha_dot_dt)
ax.set_aspect('equal')
-----------------------
pylab.quiver(x, y, u, v, angles='xy', scale_units='xy', scale=10)

ModuleNotFoundError: No module named 'airflow.providers.slack' Airflow 2.0 (MWAA)

copy iconCopydownload iconDownload
--constraint "https://raw.githubusercontent.com/apache/airflow/constraints-main/constraints-3.7.txt"

Function that calculates uncertainty

copy iconCopydownload iconDownload
>>> def ucalc(f, x, u):
...     f = S(f)
...     syms = list(ordered(f.free_symbols))
...     assert len(x) == len(u) == len(syms)
...     reps = dict(zip(syms, x))
...     ui = IndexedBase('u')
...     args = []
...     for i, xi in enumerate(syms):
...         reps[ui[xi]] = u[i]
...         args.append((ui[xi]*diff(f, xi))**2)
...     return reps, sqrt(Add(*args)).n(subs=reps)
...
>>> ucalc('2*pi*sqrt(L/g)',(9.8,5.4),(.1,.3))
({L: 9.8, g: 5.4, u[L]: 0.1, u[g]: 0.3}, 0.239055276534314)

Airflow wrong execution_date for timezone aware DAGs

copy iconCopydownload iconDownload
{{ execution_date.in_timezone('Europe/Amsterdam') }}
{{ dag_run.logical_date.astimezone(dag.timezone) }}
-----------------------
{{ execution_date.in_timezone('Europe/Amsterdam') }}
{{ dag_run.logical_date.astimezone(dag.timezone) }}

gym package not identifying ten-armed-bandits-v0 env

copy iconCopydownload iconDownload
git clone gym_armed_bandits
cd gym_armed_bandits
pip install -e .

MWAA not finding aws_default connection

copy iconCopydownload iconDownload
from airflow.hooks.base import BaseHook
conn = BaseHook.get_connection('aws_service_account')
...

print(conn.host)
print(conn.login)
print(conn.password)
[2021-11-23 13:01:02,487] {{logging_mixin.py:104}} INFO - [2021-11-23 13:01:02,486] {{base_aws.py:368}} INFO - Airflow Connection: aws_conn_id=aws_default
[2021-11-23 13:01:02,657] {{logging_mixin.py:104}} INFO - [2021-11-23 13:01:02,656] {{base_aws.py:179}} INFO - No credentials retrieved from Connection
[2021-11-23 13:01:02,678] {{logging_mixin.py:104}} INFO - [2021-11-23 13:01:02,678] {{base_aws.py:87}} INFO - Creating session with aws_access_key_id=None region_name=us-east-1
[2021-11-23 13:01:02,772] {{logging_mixin.py:104}} INFO - [2021-11-23 13:01:02,772] {{base_aws.py:157}} INFO - role_arn is None
from datetime import timedelta
from airflow import DAG
from datetime import datetime
from airflow.providers.cncf.kubernetes.operators.kubernetes_pod import KubernetesPodOperator

default_args = {
    'owner': 'aws',
    'depends_on_past': False,
    'start_date': datetime(2019, 2, 20),
    'provide_context': True
}

dag = DAG(
    'kubernetes_pod_example', default_args=default_args, schedule_interval=None
)

#use a kube_config stored in s3 dags folder for now
kube_config_path = '/usr/local/airflow/dags/kube_config.yaml'

podRun = KubernetesPodOperator(
    namespace="mwaa",
    image="ubuntu:18.04",
    cmds=["bash"],
    arguments=["-c", "ls"],
    labels={"foo": "bar"},
    name="mwaa-pod-test",
    task_id="pod-task",
    get_logs=True,
    dag=dag,
    is_delete_operator_pod=False,
    config_file=kube_config_path,
    in_cluster=False,
    cluster_context='aws',
    execution_timeout=timedelta(seconds=60)
)
-----------------------
from airflow.hooks.base import BaseHook
conn = BaseHook.get_connection('aws_service_account')
...

print(conn.host)
print(conn.login)
print(conn.password)
[2021-11-23 13:01:02,487] {{logging_mixin.py:104}} INFO - [2021-11-23 13:01:02,486] {{base_aws.py:368}} INFO - Airflow Connection: aws_conn_id=aws_default
[2021-11-23 13:01:02,657] {{logging_mixin.py:104}} INFO - [2021-11-23 13:01:02,656] {{base_aws.py:179}} INFO - No credentials retrieved from Connection
[2021-11-23 13:01:02,678] {{logging_mixin.py:104}} INFO - [2021-11-23 13:01:02,678] {{base_aws.py:87}} INFO - Creating session with aws_access_key_id=None region_name=us-east-1
[2021-11-23 13:01:02,772] {{logging_mixin.py:104}} INFO - [2021-11-23 13:01:02,772] {{base_aws.py:157}} INFO - role_arn is None
from datetime import timedelta
from airflow import DAG
from datetime import datetime
from airflow.providers.cncf.kubernetes.operators.kubernetes_pod import KubernetesPodOperator

default_args = {
    'owner': 'aws',
    'depends_on_past': False,
    'start_date': datetime(2019, 2, 20),
    'provide_context': True
}

dag = DAG(
    'kubernetes_pod_example', default_args=default_args, schedule_interval=None
)

#use a kube_config stored in s3 dags folder for now
kube_config_path = '/usr/local/airflow/dags/kube_config.yaml'

podRun = KubernetesPodOperator(
    namespace="mwaa",
    image="ubuntu:18.04",
    cmds=["bash"],
    arguments=["-c", "ls"],
    labels={"foo": "bar"},
    name="mwaa-pod-test",
    task_id="pod-task",
    get_logs=True,
    dag=dag,
    is_delete_operator_pod=False,
    config_file=kube_config_path,
    in_cluster=False,
    cluster_context='aws',
    execution_timeout=timedelta(seconds=60)
)
-----------------------
from airflow.hooks.base import BaseHook
conn = BaseHook.get_connection('aws_service_account')
...

print(conn.host)
print(conn.login)
print(conn.password)
[2021-11-23 13:01:02,487] {{logging_mixin.py:104}} INFO - [2021-11-23 13:01:02,486] {{base_aws.py:368}} INFO - Airflow Connection: aws_conn_id=aws_default
[2021-11-23 13:01:02,657] {{logging_mixin.py:104}} INFO - [2021-11-23 13:01:02,656] {{base_aws.py:179}} INFO - No credentials retrieved from Connection
[2021-11-23 13:01:02,678] {{logging_mixin.py:104}} INFO - [2021-11-23 13:01:02,678] {{base_aws.py:87}} INFO - Creating session with aws_access_key_id=None region_name=us-east-1
[2021-11-23 13:01:02,772] {{logging_mixin.py:104}} INFO - [2021-11-23 13:01:02,772] {{base_aws.py:157}} INFO - role_arn is None
from datetime import timedelta
from airflow import DAG
from datetime import datetime
from airflow.providers.cncf.kubernetes.operators.kubernetes_pod import KubernetesPodOperator

default_args = {
    'owner': 'aws',
    'depends_on_past': False,
    'start_date': datetime(2019, 2, 20),
    'provide_context': True
}

dag = DAG(
    'kubernetes_pod_example', default_args=default_args, schedule_interval=None
)

#use a kube_config stored in s3 dags folder for now
kube_config_path = '/usr/local/airflow/dags/kube_config.yaml'

podRun = KubernetesPodOperator(
    namespace="mwaa",
    image="ubuntu:18.04",
    cmds=["bash"],
    arguments=["-c", "ls"],
    labels={"foo": "bar"},
    name="mwaa-pod-test",
    task_id="pod-task",
    get_logs=True,
    dag=dag,
    is_delete_operator_pod=False,
    config_file=kube_config_path,
    in_cluster=False,
    cluster_context='aws',
    execution_timeout=timedelta(seconds=60)
)

Airflow external_task_sensor never stops poking

copy iconCopydownload iconDownload
    wait_for_parent_task = ExternalTaskSensor(
        task_id='wait_for_parent_task ',
        external_dag_id='test_parent',
        external_task_id='task_parent_2',
        check_existence=True,
        # execution_date needs to be exact (scheduled time) and the london timezone
        # Remember: The scheduled start is always the one step further in the past - 
        # For a daily schedule: - datetime.timedelta(days=1)
        execution_date_fn=lambda dt: (datetime.datetime(year=dt.year, month=dt.month, day=dt.day, tzinfo=local_tz)
                                      + datetime.timedelta(hours=6, minutes=0)
                                      - datetime.timedelta(days=1)
                                      ).astimezone(local_tz_london),
    )

How to use Gekko to solve for optimal control for a reusable reentry vehicle

copy iconCopydownload iconDownload
m.Equation(rad.dt() == vel*m.sin(fpa))
m.Equation((rad*m.cos(lat))*lon.dt() == vel*m.cos(fpa)*m.sin(azi))
m.Equation(rad*lat.dt() == vel*m.cos(fpa)*m.cos(azi))
m.Equation(vel.dt() == -D-gravity*m.sin(fpa))
m.Equation(vel*fpa.dt() == (L*m.cos(bank)-m.cos(fpa)*(gravity-vel**2/rad)))
m.Equation(m.cos(fpa)*rad*vel*azi.dt() == \
           (L*m.sin(bank)*rad+vel**2*(m.cos(fpa))**2*m.sin(azi)*m.tan(lat)))
from gekko import GEKKO
import numpy as np
import matplotlib.pyplot as plt
import math

pi = math.pi

########################
######FRONT MATTER######
########################
m = GEKKO() # initialize GEKKO
nt = 101 # 2501 #simulation time is 2500 seconds
tfin = 0.04
m.time = np.linspace(0,tfin,nt) #time array

#==================#
#PARAMS
#==================#
Re  = m.Param(value = 6371203.92)           # radius of the earth, m
S   = m.Param(value = 249.9091776)          # vehicle surface area, m^2
cl0 = m.Param(value = -0.2070)              # coeff lift param 1
cl1 = m.Param(value = 1.6756)               # coeff lift param 2
cd0 = m.Param(value = 0.0785)               # coeff drag param 1
cd1 = m.Param(value = -0.3529)              # coeff drag param 2
cd2 = m.Param(value = 2.0400)               # coeff drag param 3
H   = m.Param(value = 7254.24)              # density scale height, m
rho0= m.Param(value = 1.225570827014494)    # sea level atmospheric density, kg/m^3
mu  = m.Param(value = 3.986031954093051e14) #earth gravitational param, m^3/s^2
mass= m.Param(value = 92079.2525560557)     #vehicle mass, kg

#===============================#
#BOUNDARY CONDITIONS
#===============================#
t0     = 0
alt0   = 79248
rad0   = alt0+Re
altf   = 24384
radf   = altf+Re
lon0   = 0
lat0   = 0
speed0 = +7802.88
speedf = +762
fpa0   = -1*pi/180
fpaf   = -5*pi/180
azi0   = +90*pi/180
azif   = -90*pi/180

#===============================#
#LIMITS ON VARIABLES
#===============================#
tfMin = 0;              tfMax = 3000;
radMin = Re;            radMax = rad0;
lonMin = -pi;           lonMax = -lonMin;
latMin = -70*pi/180;    latMax = -latMin;
speedMin = 10;          speedMax = 45000;
fpaMin = -80*pi/180;    fpaMax =  80*pi/180;
aziMin = -180*pi/180;   aziMax =  180*pi/180;
aoaMin = -90*pi/180;    aoaMax = -aoaMin;
bankMin = -90*pi/180;   bankMax =   1*pi/180;

#===============================#
#VARIABLES
#===============================#

#state variables and bounds
rad = m.Var(value=rad0, lb=radMin, ub=radMax)       # radius, m
lon = m.Var(value=lon0, lb=lonMin, ub=lonMax)       # longitude, rad
lat = m.Var(value=lat0, lb=latMin, ub=latMax)       # latitude, rad
vel = m.Var(value=speed0, lb=speedMin, ub=speedMax) # velocity, m/sec
fpa = m.Var(value=fpa0, lb=fpaMin, ub=fpaMax)       # flight path angle, rad
azi = m.Var(value=azi0, lb=aziMin, ub=aziMax)       # azimuth angle, rad

#control variables
aoa     = m.MV(value=-20, lb=aoaMin, ub=aoaMax)    # angle of attack, rad
aoa.STATUS = 1
bank    = m.MV(value=0, lb=bankMin, ub=bankMax)    # bank angle, rad
bank.STATUS = 1

#===============================#
#INTERMEDIATE VARIABLES
#===============================#
altitude = rad - Re
CD       = cd0+cd1*aoa+cd2*aoa**2
rho      = rho0*m.exp(-altitude/H)
CL       = cl0+cl1*aoa
q        = 0.5*rho*vel**2
D        = q*S*CD/mass
L        = q*S*CL/mass
gravity  = mu/rad**2

#===============================#
#EOMS
#===============================#

p = np.zeros(nt) # mark final time point
p[-1] = 1.0
final = m.Param(value=p)

m.Equation(rad.dt() == vel*m.sin(fpa))
m.Equation((rad*m.cos(lat))*lon.dt() == vel*m.cos(fpa)*m.sin(azi))
m.Equation(rad*lat.dt() == vel*m.cos(fpa)*m.cos(azi))
m.Equation(vel.dt() == -D-gravity*m.sin(fpa))
m.Equation(vel*fpa.dt() == (L*m.cos(bank)-m.cos(fpa)*(gravity-vel**2/rad)))
m.Equation(m.cos(fpa)*rad*vel*azi.dt() == \
           (L*m.sin(bank)*rad+vel**2*(m.cos(fpa))**2*m.sin(azi)*m.tan(lat)))

#===============================#
#OPTIMIZATION SOLVER
#===============================#
m.Maximize(lat*final)
m.options.SOLVER = 3
m.options.IMODE = 6
m.solve(disp=True)

plt.subplot(4,2,1)
plt.plot(m.time,rad.value,label='rad')
plt.legend()
plt.subplot(4,2,2)
plt.plot(m.time,lon.value,label='lon')
plt.legend()
plt.subplot(4,2,3)
plt.plot(m.time,lat.value,label='lat')
plt.legend()
plt.subplot(4,2,4)
plt.plot(m.time,vel.value,label='vel')
plt.legend()
plt.subplot(4,2,5)
plt.plot(m.time,fpa.value,label='fpa')
plt.legend()
plt.subplot(4,2,6)
plt.plot(m.time,azi.value,label='azi')
plt.legend()
plt.subplot(4,2,7)
plt.plot(m.time,aoa.value,label='aoa')
plt.xlabel('Time')
plt.legend()
plt.subplot(4,2,8)
plt.plot(m.time,bank.value,label='bank')
plt.xlabel('Time')
plt.legend()
plt.show()
-----------------------
m.Equation(rad.dt() == vel*m.sin(fpa))
m.Equation((rad*m.cos(lat))*lon.dt() == vel*m.cos(fpa)*m.sin(azi))
m.Equation(rad*lat.dt() == vel*m.cos(fpa)*m.cos(azi))
m.Equation(vel.dt() == -D-gravity*m.sin(fpa))
m.Equation(vel*fpa.dt() == (L*m.cos(bank)-m.cos(fpa)*(gravity-vel**2/rad)))
m.Equation(m.cos(fpa)*rad*vel*azi.dt() == \
           (L*m.sin(bank)*rad+vel**2*(m.cos(fpa))**2*m.sin(azi)*m.tan(lat)))
from gekko import GEKKO
import numpy as np
import matplotlib.pyplot as plt
import math

pi = math.pi

########################
######FRONT MATTER######
########################
m = GEKKO() # initialize GEKKO
nt = 101 # 2501 #simulation time is 2500 seconds
tfin = 0.04
m.time = np.linspace(0,tfin,nt) #time array

#==================#
#PARAMS
#==================#
Re  = m.Param(value = 6371203.92)           # radius of the earth, m
S   = m.Param(value = 249.9091776)          # vehicle surface area, m^2
cl0 = m.Param(value = -0.2070)              # coeff lift param 1
cl1 = m.Param(value = 1.6756)               # coeff lift param 2
cd0 = m.Param(value = 0.0785)               # coeff drag param 1
cd1 = m.Param(value = -0.3529)              # coeff drag param 2
cd2 = m.Param(value = 2.0400)               # coeff drag param 3
H   = m.Param(value = 7254.24)              # density scale height, m
rho0= m.Param(value = 1.225570827014494)    # sea level atmospheric density, kg/m^3
mu  = m.Param(value = 3.986031954093051e14) #earth gravitational param, m^3/s^2
mass= m.Param(value = 92079.2525560557)     #vehicle mass, kg

#===============================#
#BOUNDARY CONDITIONS
#===============================#
t0     = 0
alt0   = 79248
rad0   = alt0+Re
altf   = 24384
radf   = altf+Re
lon0   = 0
lat0   = 0
speed0 = +7802.88
speedf = +762
fpa0   = -1*pi/180
fpaf   = -5*pi/180
azi0   = +90*pi/180
azif   = -90*pi/180

#===============================#
#LIMITS ON VARIABLES
#===============================#
tfMin = 0;              tfMax = 3000;
radMin = Re;            radMax = rad0;
lonMin = -pi;           lonMax = -lonMin;
latMin = -70*pi/180;    latMax = -latMin;
speedMin = 10;          speedMax = 45000;
fpaMin = -80*pi/180;    fpaMax =  80*pi/180;
aziMin = -180*pi/180;   aziMax =  180*pi/180;
aoaMin = -90*pi/180;    aoaMax = -aoaMin;
bankMin = -90*pi/180;   bankMax =   1*pi/180;

#===============================#
#VARIABLES
#===============================#

#state variables and bounds
rad = m.Var(value=rad0, lb=radMin, ub=radMax)       # radius, m
lon = m.Var(value=lon0, lb=lonMin, ub=lonMax)       # longitude, rad
lat = m.Var(value=lat0, lb=latMin, ub=latMax)       # latitude, rad
vel = m.Var(value=speed0, lb=speedMin, ub=speedMax) # velocity, m/sec
fpa = m.Var(value=fpa0, lb=fpaMin, ub=fpaMax)       # flight path angle, rad
azi = m.Var(value=azi0, lb=aziMin, ub=aziMax)       # azimuth angle, rad

#control variables
aoa     = m.MV(value=-20, lb=aoaMin, ub=aoaMax)    # angle of attack, rad
aoa.STATUS = 1
bank    = m.MV(value=0, lb=bankMin, ub=bankMax)    # bank angle, rad
bank.STATUS = 1

#===============================#
#INTERMEDIATE VARIABLES
#===============================#
altitude = rad - Re
CD       = cd0+cd1*aoa+cd2*aoa**2
rho      = rho0*m.exp(-altitude/H)
CL       = cl0+cl1*aoa
q        = 0.5*rho*vel**2
D        = q*S*CD/mass
L        = q*S*CL/mass
gravity  = mu/rad**2

#===============================#
#EOMS
#===============================#

p = np.zeros(nt) # mark final time point
p[-1] = 1.0
final = m.Param(value=p)

m.Equation(rad.dt() == vel*m.sin(fpa))
m.Equation((rad*m.cos(lat))*lon.dt() == vel*m.cos(fpa)*m.sin(azi))
m.Equation(rad*lat.dt() == vel*m.cos(fpa)*m.cos(azi))
m.Equation(vel.dt() == -D-gravity*m.sin(fpa))
m.Equation(vel*fpa.dt() == (L*m.cos(bank)-m.cos(fpa)*(gravity-vel**2/rad)))
m.Equation(m.cos(fpa)*rad*vel*azi.dt() == \
           (L*m.sin(bank)*rad+vel**2*(m.cos(fpa))**2*m.sin(azi)*m.tan(lat)))

#===============================#
#OPTIMIZATION SOLVER
#===============================#
m.Maximize(lat*final)
m.options.SOLVER = 3
m.options.IMODE = 6
m.solve(disp=True)

plt.subplot(4,2,1)
plt.plot(m.time,rad.value,label='rad')
plt.legend()
plt.subplot(4,2,2)
plt.plot(m.time,lon.value,label='lon')
plt.legend()
plt.subplot(4,2,3)
plt.plot(m.time,lat.value,label='lat')
plt.legend()
plt.subplot(4,2,4)
plt.plot(m.time,vel.value,label='vel')
plt.legend()
plt.subplot(4,2,5)
plt.plot(m.time,fpa.value,label='fpa')
plt.legend()
plt.subplot(4,2,6)
plt.plot(m.time,azi.value,label='azi')
plt.legend()
plt.subplot(4,2,7)
plt.plot(m.time,aoa.value,label='aoa')
plt.xlabel('Time')
plt.legend()
plt.subplot(4,2,8)
plt.plot(m.time,bank.value,label='bank')
plt.xlabel('Time')
plt.legend()
plt.show()

Why is it not possible to store DD-MM-YYYY format in date format?

copy iconCopydownload iconDownload
import datetime

df["Date"] = [datetime.datetime.strptime(s, '%Y-%m-%d').strftime('%d-%m-%Y') for s in df["Date"]]
df['Date'] = pd.to_datetime(df['Date'])
df['Date'] = df["Date"].dt.strftime("%d-%m-%Y")
df['Date'] = pd.to_datetime(df['Date']).dt.strftime("%d-%m-%Y")
-----------------------
import datetime

df["Date"] = [datetime.datetime.strptime(s, '%Y-%m-%d').strftime('%d-%m-%Y') for s in df["Date"]]
df['Date'] = pd.to_datetime(df['Date'])
df['Date'] = df["Date"].dt.strftime("%d-%m-%Y")
df['Date'] = pd.to_datetime(df['Date']).dt.strftime("%d-%m-%Y")
-----------------------
import datetime

df["Date"] = [datetime.datetime.strptime(s, '%Y-%m-%d').strftime('%d-%m-%Y') for s in df["Date"]]
df['Date'] = pd.to_datetime(df['Date'])
df['Date'] = df["Date"].dt.strftime("%d-%m-%Y")
df['Date'] = pd.to_datetime(df['Date']).dt.strftime("%d-%m-%Y")

Why is my css svg animation stuttering on Firefox and not on other browsers?

copy iconCopydownload iconDownload
function startPendulum() {
  let animEls = document.querySelector('[class*="animate-pendulum"]');
  animEls.classList.replace('--animate-pendulum', 'animate-pendulum');
}

function startPendulumStar() {
  let animEls = document.querySelector('[class*="animate-star"]');
  animEls.classList.replace('--animate-star', 'animate-star');
}

function addTransform() {
  let animEls = document.querySelector('[class*="pendulum-transform"]');
  animEls.classList.replace('--pendulum-transform', 'pendulum-transform');
}
.pendulum-wrp {
  background-color: rgba(0, 0, 255, 0.517);
  display: inline-block;
  width: 50%;
}

.transformBox-fill-box {
  transform-box: fill-box;
}

.pendulum-star {
  fill: #00ff00;
  transform-origin: center center;
  fill: #00ff00;
  fill-opacity: 0.517647;
  stroke: #000000;
  stroke-width: 4;
  stroke-linecap: butt;
  stroke-linejoin: miter;
}

.pendulum-rod {
  fill: rgba(0, 0, 255, 0.5);
  stroke: #000000;
  stroke-width: 4
}

.pendulum-group {
  transform-origin: center top;
}

.pendulum-transform {
  transform: translate(-20%, 5%);
}

.animate-star .pendulum-star {
  animation-name: pendulum-anim;
  animation-duration: 2s;
  animation-iteration-count: infinite;
  animation-fill-mode: forwards;
}

.animate-pendulum .pendulum-group {
  animation-name: pendulum-anim;
  animation-duration: 4s;
  animation-iteration-count: infinite;
  animation-fill-mode: forwards;
}

@keyframes pendulum-anim {
  0%,
  100% {
    transform: rotate(45deg);
  }
  50% {
    transform: rotate(-45deg);
  }
}
<div class="pendulum-wrp --animate-pendulum  --animate-star">
  <svg viewBox="0 0 1366 768" id="SVGRoot" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg">
  <g id="pendulum-transform" class="--pendulum-transform">
    <g id="pendulum-group" class="pendulum-group --transformBox-fill-box">
      <rect id="pendulum-rod" class="pendulum-rod" x="673" y="0" width="10" height="354" />
      <g id="pendulum-star" class="pendulum-star transformBox-fill-box">
        <path class="pendulum-star-shape" d="M677.667 383.157l-34.609 18.195l6.609-38.539l-28-27.293l38.694-5.623l17.306-35.064l17.306 35.064l38.693 5.623l-28 27.293l6.609 38.539l-34.608-18.195z" />
      </g>
    </g>
  </g>
</svg>
</div>
<p>
  <button  onclick="startPendulum()">Start pendulum animation</button>
  <button  onclick="startPendulumStar()">Start star animation</button>
  <button  onclick="addTransform()">shift by transform</button>
</p>
-----------------------
function startPendulum() {
  let animEls = document.querySelector('[class*="animate-pendulum"]');
  animEls.classList.replace('--animate-pendulum', 'animate-pendulum');
}

function startPendulumStar() {
  let animEls = document.querySelector('[class*="animate-star"]');
  animEls.classList.replace('--animate-star', 'animate-star');
}

function addTransform() {
  let animEls = document.querySelector('[class*="pendulum-transform"]');
  animEls.classList.replace('--pendulum-transform', 'pendulum-transform');
}
.pendulum-wrp {
  background-color: rgba(0, 0, 255, 0.517);
  display: inline-block;
  width: 50%;
}

.transformBox-fill-box {
  transform-box: fill-box;
}

.pendulum-star {
  fill: #00ff00;
  transform-origin: center center;
  fill: #00ff00;
  fill-opacity: 0.517647;
  stroke: #000000;
  stroke-width: 4;
  stroke-linecap: butt;
  stroke-linejoin: miter;
}

.pendulum-rod {
  fill: rgba(0, 0, 255, 0.5);
  stroke: #000000;
  stroke-width: 4
}

.pendulum-group {
  transform-origin: center top;
}

.pendulum-transform {
  transform: translate(-20%, 5%);
}

.animate-star .pendulum-star {
  animation-name: pendulum-anim;
  animation-duration: 2s;
  animation-iteration-count: infinite;
  animation-fill-mode: forwards;
}

.animate-pendulum .pendulum-group {
  animation-name: pendulum-anim;
  animation-duration: 4s;
  animation-iteration-count: infinite;
  animation-fill-mode: forwards;
}

@keyframes pendulum-anim {
  0%,
  100% {
    transform: rotate(45deg);
  }
  50% {
    transform: rotate(-45deg);
  }
}
<div class="pendulum-wrp --animate-pendulum  --animate-star">
  <svg viewBox="0 0 1366 768" id="SVGRoot" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg">
  <g id="pendulum-transform" class="--pendulum-transform">
    <g id="pendulum-group" class="pendulum-group --transformBox-fill-box">
      <rect id="pendulum-rod" class="pendulum-rod" x="673" y="0" width="10" height="354" />
      <g id="pendulum-star" class="pendulum-star transformBox-fill-box">
        <path class="pendulum-star-shape" d="M677.667 383.157l-34.609 18.195l6.609-38.539l-28-27.293l38.694-5.623l17.306-35.064l17.306 35.064l38.693 5.623l-28 27.293l6.609 38.539l-34.608-18.195z" />
      </g>
    </g>
  </g>
</svg>
</div>
<p>
  <button  onclick="startPendulum()">Start pendulum animation</button>
  <button  onclick="startPendulumStar()">Start star animation</button>
  <button  onclick="addTransform()">shift by transform</button>
</p>
-----------------------
function startPendulum() {
  let animEls = document.querySelector('[class*="animate-pendulum"]');
  animEls.classList.replace('--animate-pendulum', 'animate-pendulum');
}

function startPendulumStar() {
  let animEls = document.querySelector('[class*="animate-star"]');
  animEls.classList.replace('--animate-star', 'animate-star');
}

function addTransform() {
  let animEls = document.querySelector('[class*="pendulum-transform"]');
  animEls.classList.replace('--pendulum-transform', 'pendulum-transform');
}
.pendulum-wrp {
  background-color: rgba(0, 0, 255, 0.517);
  display: inline-block;
  width: 50%;
}

.transformBox-fill-box {
  transform-box: fill-box;
}

.pendulum-star {
  fill: #00ff00;
  transform-origin: center center;
  fill: #00ff00;
  fill-opacity: 0.517647;
  stroke: #000000;
  stroke-width: 4;
  stroke-linecap: butt;
  stroke-linejoin: miter;
}

.pendulum-rod {
  fill: rgba(0, 0, 255, 0.5);
  stroke: #000000;
  stroke-width: 4
}

.pendulum-group {
  transform-origin: center top;
}

.pendulum-transform {
  transform: translate(-20%, 5%);
}

.animate-star .pendulum-star {
  animation-name: pendulum-anim;
  animation-duration: 2s;
  animation-iteration-count: infinite;
  animation-fill-mode: forwards;
}

.animate-pendulum .pendulum-group {
  animation-name: pendulum-anim;
  animation-duration: 4s;
  animation-iteration-count: infinite;
  animation-fill-mode: forwards;
}

@keyframes pendulum-anim {
  0%,
  100% {
    transform: rotate(45deg);
  }
  50% {
    transform: rotate(-45deg);
  }
}
<div class="pendulum-wrp --animate-pendulum  --animate-star">
  <svg viewBox="0 0 1366 768" id="SVGRoot" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg">
  <g id="pendulum-transform" class="--pendulum-transform">
    <g id="pendulum-group" class="pendulum-group --transformBox-fill-box">
      <rect id="pendulum-rod" class="pendulum-rod" x="673" y="0" width="10" height="354" />
      <g id="pendulum-star" class="pendulum-star transformBox-fill-box">
        <path class="pendulum-star-shape" d="M677.667 383.157l-34.609 18.195l6.609-38.539l-28-27.293l38.694-5.623l17.306-35.064l17.306 35.064l38.693 5.623l-28 27.293l6.609 38.539l-34.608-18.195z" />
      </g>
    </g>
  </g>
</svg>
</div>
<p>
  <button  onclick="startPendulum()">Start pendulum animation</button>
  <button  onclick="startPendulumStar()">Start star animation</button>
  <button  onclick="addTransform()">shift by transform</button>
</p>

Community Discussions

Trending Discussions on pendulum
  • Matplotlib plot of ODE solution is not tangential to RHS vector field
  • ModuleNotFoundError: No module named 'airflow.providers.slack' Airflow 2.0 (MWAA)
  • Function that calculates uncertainty
  • Android build failed. showing &quot;Resource compilation failed. Check logs for details.&quot;
  • Issues while running tutorials of Drake programs, in Underactuated Robotics document, in Deepnote?
  • Pymongo vs pyscopg3: orders of magnitude difference for writes?
  • pandas datetime column, comparing to datetime variables: TypeError: can't compare offset-naive and offset-aware datetimes
  • MultibodyPlant’s dynamics as part of a Python function/lambda constraint in a MathematicalProgram for direct collocation from scratch
  • Airflow wrong execution_date for timezone aware DAGs
  • gym package not identifying ten-armed-bandits-v0 env
Trending Discussions on pendulum

QUESTION

Matplotlib plot of ODE solution is not tangential to RHS vector field

Asked 2022-Apr-15 at 17:51

I am experimenting with oridnary differential equations and for that I programmed a little code that plots the trajectory of a pendulum in phase space. However, the trajectory isn't really tangential to the vector field given by the right hand side of the ODE as it is supposed to be. Is this a plotting issue? As I use the same function of the ODE for both the numerical integration and plotting of the vector field I dont know how this can happen...

Resulting plot

import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import solve_ivp

# Constants
g = 9.81
l = 1
delta = 0.6

# Initial state vector: [alpha, dalpha_dot]
x0 = np.array([-6, 8])

# Right hand side od pendulum ODE
def pendulum_rhs(t, y):
    return np.array([y[1], g/l * np.sin(y[0]) - delta * y[1]])

# Solve ODE using runge kutta method
ode_sol = solve_ivp (pendulum_rhs, [0, 10], x0, dense_output=True, t_eval=np.linspace(0 ,10, 200))

ode_sol_y = ode_sol.y.T

# Get the vector field along the trajectory
draw_arrow_every_nth = 5
vector_field_at_ode_sol_y = np.array([pendulum_rhs(0, curr_y) for curr_y in ode_sol_y[::draw_arrow_every_nth, :]])

# create whole vector field
alpha = np.linspace(-2*np.pi, 2*np.pi, 21)
alpha_dot = np.linspace(-10, 10, 21)
# full coorindate arrays
alpha_2dgrid, alpha_dot_2dgrid = np.meshgrid(alpha, alpha_dot)

alpha_dt = alpha_dot_2dgrid
alpha_dot_dt = g/l * np.sin(alpha_2dgrid) - delta * alpha_dot_2dgrid

# Plotting
plt.figure()
plt.quiver(alpha_2dgrid, alpha_dot_2dgrid,
       alpha_dt, alpha_dot_dt)
plt.plot(ode_sol_y[:,0], ode_sol_y[:,1])
plt.quiver(ode_sol_y[::draw_arrow_every_nth, 0], ode_sol_y[::draw_arrow_every_nth, 1], vector_field_at_ode_sol_y[:,0], vector_field_at_ode_sol_y[:,1])

ANSWER

Answered 2022-Apr-15 at 17:25

This looks like an aspect issue. You could add ax.set_aspect('equal') to get the result you want.

See code below:

# Plotting
fig,ax=plt.subplots(figsize=(8,8))
ax.plot(ode_sol_y[:,0], ode_sol_y[:,1])
plt.quiver(ode_sol_y[::draw_arrow_every_nth, 0], ode_sol_y[::draw_arrow_every_nth, 1], vector_field_at_ode_sol_y[:,0], vector_field_at_ode_sol_y[:,1])
plt.quiver(alpha_2dgrid, alpha_dot_2dgrid,alpha_dt, alpha_dot_dt)
ax.set_aspect('equal')

And the output gives:

enter image description here

Source https://stackoverflow.com/questions/71886382

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install pendulum

You can download it from GitHub.
You can use pendulum like any standard Python library. You will need to make sure that you have a development environment consisting of a Python distribution including header files, a compiler, pip, and git installed. Make sure that your pip, setuptools, and wheel are up to date. When using pip it is generally recommended to install packages in a virtual environment to avoid changes to the system.

Support

For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

Explore Related Topics

Share this Page

share link
Reuse Pre-built Kits with pendulum
Consider Popular Date Time Utils Libraries
Compare Date Time Utils Libraries with Highest Support
Compare Date Time Utils Libraries with Permissive License
Compare Date Time Utils Libraries with Highest Reuse
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.