Graph flattened on the y's axe - graph

I am trying to draw a hypotrochoïde figure, but my graph is flattened on the axes of y. I cann'ot find the error. Please help me! Thank you in advance! :)
#Définir la fonction hypotrochoïde
def hypo(R,r,d,phi0=0,color='k'):
"""
Cette fonction calcule la position du crayon en fonction de phi.
Par défaut, la valeur de "phi0" est égale à zéro et la valeur de "c" \
est égale à la couleur noire, soit 'color=k'.
"""
if R<1000 and r<1000 and d<1000 :
x=(R-r)*np.cos(thêta)+d*(np.cos(-((R-r)/r)*thêta+phi0))
y=(R-r)*np.sin(thêta)+d*(np.sin(-((R-r)/r)*thêta+phi0))
else:
print('Erreur! Les valeurs de R, r et d sont restreint à des \
nombres entiers entre 0 et 1000. ')
return x,y
#L'utilisateur entre les valeurs de R, r et d
valeurR=input("SVP entrez la valeur de R :")
vR=float(valeurR)
R=int(vR)
valeurr=input("SVP entrez la valeur de r :")
vr=float(valeurr)
r=int(vr)
valeurd=input("SVP entrez la valeur de d :")
vd=float(valeurd)
d=int(vd)
#Calculer la valeur de n (entier positif)
m=r
n=(r/(R-r))*m
#Calculer le nombres de tours
thêta=np.linspace(0,2*n*np.pi,100)
#Affichage du graphique
plt.plot(hypo(R, r, d))
plt.axis('equal')
plt.title("Hypotrochoïdes")
plt.xlabel('x')
plt.ylabel('y')
plt.grid()
plt.show()

Related

Unicode in string is giving problems for replacement

I am working with strings in R. My issue rises with a special character that is not allowing to replace the strings properly. I do some replacement to extract a text between __ and _ but it is not working for last examples. The code is next:
#Extract
y$Extract <- gsub(".*[_]{2}([^_]+)[_].*", "\\1",gsub('\n\n','_',y$Var))
The data used is:
#Data
y <- structure(list(Var = c("\n\n\nEl sector turístico en Mexico: análisis de la incidencia de la pandemia de la Covid-19 en el margen bruto, y propuesta de mejora para los hoteles 5 estrellas ubicados en la provincia de Taco, cantón Taco, parroquia GX\n\n <U+FEFF> \n \n\n\n\nCabezas Vásquez, Dayanna Gabriela\n (UNAM - TEC, 2022-07-01)\n\nLa presencia del Coronavirus sin duda ha provocado desestabilización en uno de los sectores más perjudicados, que es el hotelero, ya que cuando hubo la pandemia, en Ecuador y en todo el mundo, se tomaron medidas de ...\n\n",
"\n\n\nAnálisis de costos y rentabilidad años 2018 al 2020 para industrias manufactureras de tamaño grande con mayores ingresos orientados a mercados regionales, subsector elaboración de productos alimenticios y bebidas en Mexico\n\n <U+FEFF> \n \n\n\n\nAlbarracín Cedeño, Madelaine Nicole\n (ITAM - CAS, 2022-06-01)\n\nEl presente trabajo de titulación se enfoca en analizar los costos y rentabilidad de los años 2018 al 2020 para industrias manufactureras de tamaño grande con mayores ingresos orientados a mercados regionales, ...\n\n",
"\n\n\nPlan de negocios para la implementación de una empresa de asesoría de bodas ubicada en el Distrito Mexicano\n\n <U+FEFF> \n \n\n\n\nAndrade Totoy, Gabriela Abigail\n (ITAM, 2022-06-01)\n\nEste trabajo tiene como objetivo la realización de un plan de negocios dentro del mundo de la planificación de bodas y el asesoramiento que se podría brindar dentro de la cuidad de Mexico. Dentro de este trabajo se ...\n\n",
"\n\n\nDiseño de un sistema de gestión de la calidad basado en la norma Iso 9001:2008 para los procesos relacionados con el cliente en la empresa la Competencia S.A.\n\n <U+FEFF> \n \n\n\nCadena Echeverría, Jaime Luis Hermel* (TEC, 2014)\n\nEn el presente trabajo se ha diseñado la documentación requerida para un sistema de\r\ngestión de la calidad basado en la Norma ISO 9001:2008 de los procesos relacionados con\r\nel cliente de la empresa La Competencia S.A., ...\n\n",
"\n\n\nDiseño e implementación de un modelo de marketing basado en estrategias para un crecimiento continuo, con innovación y financiamiento para la Empresa Jocotours Cia. Ltda., en el Distrito Mexicano para el año 2015\n\n <U+FEFF> \n \n\n\nSánchez García, Roberto Carlos* (TEC, 2015)\n\nLa empresa Jocotours fue creada en el año 2010 con el propósito de mejorar el turismo de su organización relacionada Fundación de Conservación Jocotoco, una entidad que se dedica a la conservación de las aves amenazadas ...\n\n",
"\n\n\nPlan de negocios para la explotación técnica, ecónomica y ecológica de una mina de agregados pétreos en la parroquia de Chilos\n\n <U+FEFF> \n \n\n\nAutor desconocido (TEC / 2011, 2011-03)\n\nEl presente trabajo de disertación de desenvuelve como un proyecto de gestión de riesgos y salud ocupacional de la TEC, el cual abarca la implementación, desarrollo, manteniemiento y control del sistema de gestión de ...\n\n"
)), row.names = c(NA, -6L), class = "data.frame")
But the output for final three rows is wrong (sorry for image, print is too large):
It should be similar to first rows with the names and year. I think the unicode is doing something to text and I do not know how to solve it.
Many thanks for your help.
Instead of using multiple gsub, we could extract if the pattern is similar across the elements - here the pattern matched is one or more characters (.*) till the unicode character (<U+..>) followed by one or more spaces (\\s+), newlines (\\n+) another set of space, newline (\\s+\\n+), then match the characters that are not a closing bracket ([^)]+) followed by a closing bracket (\\)) and capture those within (...)). In the replacement, specify the backreference (\\1) of the captured substring
sub(".*\\<U\\+[^>]+>\\s+\n+\\s+\\n+([^)]+\\))\n.*", "\\1", y$Var)
[1] "Cabezas Vásquez, Dayanna Gabriela\n (UNAM - TEC, 2022-07-01)"
[2] "Albarracín Cedeño, Madelaine Nicole\n (ITAM - CAS, 2022-06-01)"
[3] "Andrade Totoy, Gabriela Abigail\n (ITAM, 2022-06-01)"
[4] "Cadena Echeverría, Jaime Luis Hermel* (TEC, 2014)"
[5] "Sánchez García, Roberto Carlos* (TEC, 2015)"
[6] "Autor desconocido (TEC / 2011, 2011-03)"
Or can be also
sub(".*\n{2,}([^(]+[()][^)]+\\)).*", "\\1", y$Var)
[1] "Cabezas Vásquez, Dayanna Gabriela\n (UNAM - TEC, 2022-07-01)"
[2] "Albarracín Cedeño, Madelaine Nicole\n (ITAM - CAS, 2022-06-01)"
[3] "Andrade Totoy, Gabriela Abigail\n (ITAM, 2022-06-01)"
[4] "Cadena Echeverría, Jaime Luis Hermel* (TEC, 2014)"
[5] "Sánchez García, Roberto Carlos* (TEC, 2015)"
[6] "Autor desconocido (TEC / 2011, 2011-03)"

Get gtin from <script type="application/ld+json"> using regex and/or xpath | source code

I need to extract the gtin value (8806090325632)
I need to get the xpath expression to scrape the 13 digit gtin code only.
Here is the <script type="application/ld+json"> code :
<script type="application/ld+json"> {"#type":"Product","aggregateRating":{"#type":"AggregateRating","ratingValue":4.4946996466431095,"ratingCount":566,"bestRating":5.0,"worstRating":1.0},"brand":{"#type":"Organization","name":"SAMSUNG"},"description":"SAMSUNG 65TU7022 TV LED 4K - 65 \" (163cm) - HDR10 + - Dolby Digital Plus - Smart TV - 2xHDMI - 1xUSB - Classe énergétique G","gtin":"8806090325632","offers":{"#type":"Offer","availability":"InStock","itemCondition":"NewCondition","price":615.99,"priceCurrency":"EUR","priceValidUntil":"2022-04-06T14:57:01.7797852+02:00","url":"https://www.cdiscount.com/high-tech/televiseurs/samsung-65tu7022-tv-led-4k-uhd-65-163-cm-h/f-1062613-samue65tu7022.html?idOffre=639618765"},"productID":"SAMUE65TU7022","category":"Téléviseur LED","sku":"samue65tu7022","review":[{"#type":"Review","reviewRating":{"#type":"Rating","bestRating":"5","ratingValue":"5","worstRating":"1"},"author":"Soso","datePublished":"2022-04-03T03:54:10","description":"Je recommande cet achat tout est parfait","name":"Parfait"},{"#type":"Review","reviewRating":{"#type":"Rating","bestRating":"5","ratingValue":"4","worstRating":"1"},"author":"SmashingQuasar","datePublished":"2022-04-02T14:13:11","description":"Cette télévision est grande et offre une résolution 4K pour un prix abordable. La qualité d'image est correcte sans être exceptionnelle. Le HDR est anecdotique sur ce modèle, on ne le discerne presque pas. 4 étoiles pour ce modèle simplement car la profondeur de noir est insatisfaisante. En dehors de ça, une assez bonne affaire pour ceux qui souhaitent passer à la 4K.","name":"Une grande TV 4K peu chère"},{"#type":"Review","reviewRating":{"#type":"Rating","bestRating":"5","ratingValue":"5","worstRating":"1"},"author":"luna","datePublished":"2022-04-01T07:40:28","description":"Sa taille et les options sont au top…","name":"TRES BON CHOIX"},{"#type":"Review","reviewRating":{"#type":"Rating","bestRating":"5","ratingValue":"4","worstRating":"1"},"author":"Sylva","datePublished":"2022-03-28T13:27:19","description":"Je viens d'acheter ce téléviseur mais malheureusement pas de connection Bluetooth possible. S'il faille le contacter avec avec une barre de son Bluetooth n'y rêvez même pas. A part ça tout est parfait pour l'instant","name":"Pas de connexion Bluetooth possible"},{"#type":"Review","reviewRating":{"#type":"Rating","bestRating":"5","ratingValue":"4","worstRating":"1"},"author":"Mortimer","datePublished":"2022-03-27T20:07:23Z","description":"L'image est superbe, quant à ses fonctionnalités, elles sont tellement nombreuses que je n'ai encore pas eu le temps de toutes les tester...","name":"Une belle bête !"}],"#context":"https://schema.org","name":"SAMSUNG 65TU7022 TV LED 4K UHD - 65 \" (163 cm) - HDR10 + - Dolby Digital Plus - Smart TV - 2xHDMI - 1xUSB","image":"https://www.cdiscount.com/pdt2/0/2/2/4/550x550/samue65tu7022/rw/samsung-65tu7022-tv-led-4k-uhd-65-163-cm-h.jpg","url":"https://www.cdiscount.com/high-tech/televiseurs/samsung-65tu7022-tv-led-4k-uhd-65-163-cm-h/f-1062613-samue65tu7022.html"}</script>
While there is no explicit language tag mentioned this answer point out approach with python.
Select the <script> from HTML and load extracted text with json.loads():
data = json.loads(soup.select_one('script[type="application/ld+json"]').text)
Now you could pick the gtin by key:
data['gtin']
Example
html = r'''<script type="application/ld+json">{"#type":"Product","aggregateRating":{"#type":"AggregateRating","ratingValue":4.4946996466431095,"ratingCount":566,"bestRating":5.0,"worstRating":1.0},"brand":{"#type":"Organization","name":"SAMSUNG"},"description":"SAMSUNG 65TU7022 TV LED 4K - 65 \" (163cm) - HDR10 + - Dolby Digital Plus - Smart TV - 2xHDMI - 1xUSB - Classe énergétique G","gtin":"8806090325632","offers":{"#type":"Offer","availability":"InStock","itemCondition":"NewCondition","price":615.99,"priceCurrency":"EUR","priceValidUntil":"2022-04-06T14:57:01.7797852+02:00","url":"https://www.cdiscount.com/high-tech/televiseurs/samsung-65tu7022-tv-led-4k-uhd-65-163-cm-h/f-1062613-samue65tu7022.html?idOffre=639618765"},"productID":"SAMUE65TU7022","category":"Téléviseur LED","sku":"samue65tu7022","review":[{"#type":"Review","reviewRating":{"#type":"Rating","bestRating":"5","ratingValue":"5","worstRating":"1"},"author":"Soso","datePublished":"2022-04-03T03:54:10","description":"Je recommande cet achat tout est parfait","name":"Parfait"},{"#type":"Review","reviewRating":{"#type":"Rating","bestRating":"5","ratingValue":"4","worstRating":"1"},"author":"SmashingQuasar","datePublished":"2022-04-02T14:13:11","description":"Cette télévision est grande et offre une résolution 4K pour un prix abordable. La qualité d'image est correcte sans être exceptionnelle. Le HDR est anecdotique sur ce modèle, on ne le discerne presque pas. 4 étoiles pour ce modèle simplement car la profondeur de noir est insatisfaisante. En dehors de ça, une assez bonne affaire pour ceux qui souhaitent passer à la 4K.","name":"Une grande TV 4K peu chère"},{"#type":"Review","reviewRating":{"#type":"Rating","bestRating":"5","ratingValue":"5","worstRating":"1"},"author":"luna","datePublished":"2022-04-01T07:40:28","description":"Sa taille et les options sont au top…","name":"TRES BON CHOIX"},{"#type":"Review","reviewRating":{"#type":"Rating","bestRating":"5","ratingValue":"4","worstRating":"1"},"author":"Sylva","datePublished":"2022-03-28T13:27:19","description":"Je viens d'acheter ce téléviseur mais malheureusement pas de connection Bluetooth possible. S'il faille le contacter avec avec une barre de son Bluetooth n'y rêvez même pas. A part ça tout est parfait pour l'instant","name":"Pas de connexion Bluetooth possible"},{"#type":"Review","reviewRating":{"#type":"Rating","bestRating":"5","ratingValue":"4","worstRating":"1"},"author":"Mortimer","datePublished":"2022-03-27T20:07:23Z","description":"L'image est superbe, quant à ses fonctionnalités, elles sont tellement nombreuses que je n'ai encore pas eu le temps de toutes les tester...","name":"Une belle bête !"}],"#context":"https://schema.org","name":"SAMSUNG 65TU7022 TV LED 4K UHD - 65 \" (163 cm) - HDR10 + - Dolby Digital Plus - Smart TV - 2xHDMI - 1xUSB","image":"https://www.cdiscount.com/pdt2/0/2/2/4/550x550/samue65tu7022/rw/samsung-65tu7022-tv-led-4k-uhd-65-163-cm-h.jpg","url":"https://www.cdiscount.com/high-tech/televiseurs/samsung-65tu7022-tv-led-4k-uhd-65-163-cm-h/f-1062613-samue65tu7022.html"}</script>'''
soup = BeautifulSoup(html)
data = json.loads(soup.select_one('script[type="application/ld+json"]').text)
data['gtin']

R sweave don't print figure

I'm using R Sweave, but r does not generate the figure. There may be a conflict in the packages or not. Which is the error.See line 73, in section * {Exercise I}, notice that in the chunk I am using fig = TRUE. Attached my code.
\documentclass[10 pt]{article}
\usepackage[spanish,activeacute]{babel}
\usepackage[latin1]{inputenc}
\usepackage{amsmath, amssymb, amsthm, latexsym, graphics, graphpap, layout, multicol, enumerate}
\usepackage{graphicx,color}
\DeclareGraphicsExtensions{.eps}
\usepackage{geometry}
\usepackage{pstricks-add}
\geometry{verbose}
\usepackage{movie15}
\usepackage{hyperref}
\usepackage{fancyhdr}
\hypersetup{bookmarksopen,bookmarksnumbered,colorlinks,linkcolor=blue,legalpaper,pagebackref,pdftitle=Parcial 1 Varias Variables,pdfauthor=Wilmer Pineda,pdfsubject=álgebra,pdfkeywords=álgebra}
\parindent=0pt
\definecolor {este}{gray}{0.9}
\definecolor{otro}{rgb}{0.56,0.65,0.76}
\definecolor{light-gray}{gray}{0.93}
\renewcommand\tablename{Tabla}
\theoremstyle{plain}
\newtheorem{prop}{Proposición}[section]
\newtheorem{teo}[prop]{Teorema}
\newtheorem{cor}[prop]{Corolario}
\newtheorem{lem}[prop]{Lema}
\theoremstyle{definition}
\newtheorem{defi}{Definición}[section]
\newtheorem{ejem}{Ejemplo}[section]
\theoremstyle{remark}
\newtheorem*{nota}{Nota}
\newtheorem*{notac}{Notación}
\makeatletter
\newenvironment{tablaqui}
{\def\#captype{table}}
{}
\newenvironment{figuraqui}
{\def\#captype{figure}}
{}
\makeatother
\pagestyle{fancy}
\headheight=80pt %para cambiar el tamaño del encabezado
\fancyhead[L] %la "L" indica a la izquierda
{
\begin{minipage}{2cm}
%\includegraphics[width=\textwidth]{LogoEAN.eps}
\end{minipage}
}
\fancyhead[C] %la "C" indica al centro
{
\textbf
{Parcial 4}} %textsf es un tipo de letra
\fancyhead[R] %la "R" indica a la derecha
{\begin{minipage}{5cm}
\begin{flushright}
Wilmer Pineda\\
Fundamentos Sistemas Continuos Gr. 1\\
13 de Junio de 2017
\end{flushright}
\end{minipage}
}
%\title{\textbf{Parcial 2}}
%\author{Carlos Isaac Zainea\\ Álgebra Lineal \\ Universidad Francisco José de Caldas}
%\date{25 de Abril de 2013}
\begin{document}
\SweaveOpts{concordance=TRUE}
Este es un examen \textbf{individual}. No se permite el uso de libros, apuntes o cualquier medio electrónico. Los celulares deben estar \textbf{apagados} durante todo el examen. Las respuestas deben estar justificadas.
\section*{Ejercicio I}
Encuentre la longitud de la gráfica $x=\frac{1}{3}\sqrt{y}(y-3)$ en el intervalo [1,9].
\begin{figure}[h]
\caption{Gráfica ejercicio 1.}
<<fig=TRUE,echo=FALSE>>=
y=seq(1,9,0.01)
x=(1/3)*sqrt(y)*(y-3)
plot(x,y,type="l")
#
\end{figure}
\section*{Ejercicio II}
Encuentre el área de la superficie que se forma al girar la gráfica de $x=\frac{1}{3}(y^2+2)^{3/2}$ en el intervalo $1\leq y \leq 2$ alrededor del eje $x$.
\section*{Ejercicio III}
Calcular las coordenadas del centro de masa del área comprendida entre las parábolas $y^2=x$ y $x^2=-8y$.
\section*{Ejercicio IV}
Un tanque tiene la forma de un cono circular invertido con longitud $10m$ y radio de la base $4m$. Se llena de agua hasta una altura de $8m$. Encuentre el trabajo requerido para vaciar el tanque bombeando toda el agua a la parte superior del tanque. (La densidad del agua es $1000kg/m^3$)
\section*{Ejercicio V}
Encuentre el volumen del sólido obtenida al girar la región comprendida entre $y=1+\sec(x)$ y $y=3$ alrededor de la recta $y=1$.
\section*{Ejercicio VI}
Las curvas de las funciones seno y coseno se intersecan infinitas veces, dando lugar a regiones de igual área. Calcular el área de una de dichas regiones.
\end{document}
To be specific this is the line that generates the error
\begin{figure}[h]
\caption{Gráfica ejercicio 1.}
<<fig=TRUE,echo=FALSE>>=
y=seq(1,9,0.01)
x=(1/3)*sqrt(y)*(y-3)
plot(x,y,type="l")
#
\end{figure}
The problem is that you are using .eps extension, so you should use the following code.
\DeclareGraphicsExtensions{.eps}
\begin{figure}[h]
\caption{Gráfica ejercicio 1.}
<<fig=TRUE,echo=FALSE, pdf=FALSE, eps=TRUE, png=TRUE>>=
y=seq(1,9,0.01)
x=(1/3)*sqrt(y)*(y-3)
plot(x,y,type="l")
#
\end{figure}

Transform web text in Spanish to ASCII

I'm using R to do text mining. I have downloaded html files. I have issues trying to convert to text because the language is Spanish.
I used:
text<-readLines(i,encoding="UTF-8")
But still, I could have text like:
prueba= "hizo la diagonal desde la izquierda hacia el centro y
combinó con Ãngel Di María, quien despachó el centro desd e la
derecha con el revés de la zurda para que Sergio Agüero empujara en
la entrada del área chica."
Where combinó=combinó, área=área, etc. I need to keep only the original alphabetic characters.
I could have another text like the following:
prueba2="El club Atlas, de la Primera D, está en la
constante búsqueda de crecimiento. Y en esa
búsqueda, consiguió un aliado de lujo. El
presidente Maxi Ambrosio viajó al Vaticano y tras
entregarle una camiseta al Papa, le pidió al propio
Francisco que adopte a los de General Rodríguez como su
segundo equipo, después de San Lorenzo. La
reacción fue positiva"
where, for example, "después" means "después"
I tried:
iconv(prueba,to="ASCII//TRANSLIT")
But I get the same text.
How can I transform the text to ASCII?

sort negative value in Unix

I have a problem when i want to sort a file like this
ce point de l ordre du jour -0.000000004070935
au sein de la commission des libertés 0.000000004017626
du conseil de sécurité de l onu -0.000000003909216
I try with this command
sort -ngk8r file1 > file2
but i get this
ce point de l ordre du jour -0.000000004070935
au sein de la commission des libertés 0.000000004017626
du conseil de sécurité de l onu -0.000000003909216
As you see the file is not sorted
I found joy by dropping the -g
$ sort -gnrk8 file1
sort: options `-gn' are incompatible
Example
$ sort -nrk8 file1
au sein de la commission des libertés 0.000000004017626
du conseil de sécurité de l onu -0.000000003909216
ce point de l ordre du jour -0.000000004070935

Resources