content
stringlengths 7
1.05M
|
---|
# add this file to your .gitignore file of the project
LOCAL_SETTINGS = dict(
media_root='/Users/user/projects/project/media',
path='/Users/user/projects/project',
virtualenv_path='/Users/user/virtualenvs/project',
)
|
# Copyright (c) 2022 {{cookiecutter.author_name}}
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
"""Version information for {{cookiecutter.project_name}}.
This file is imported by ``{{cookiecutter.package_name}}.__init__``, and parsed by
``setup.py``.
"""
# Note, that dev versions must have an extra dot compared to alpha/beta/rc
# versions in the version string. Examples:
#
# Correct: "1.0.0.dev0" and "1.0.0a1"
# Incorrect: "1.0.0dev0" and "1.0.0.a1"
#
# See PEP 0440 for details - https://www.python.org/dev/peps/pep-0440
__version__ = '1.0.0.dev1'
|
"""
Application ID: 512001308941.
Публичный ключ приложения: COAKPIKGDIHBABABA.
Секретный ключ приложения: 95C3FB547F430B544E82D448.
Вечный session_key:tkn14YgWQ279xMzvjdfJtJuRajPvJtttKSCdawotwIt7ECm6L0PzFZLqwEpBQVe3xGYr7
Session_secret_key:b2208fc58999b290093183f6fdfa6804
""" |
media_locale = {}
_NEW_PARTICIPANT = {
'ADD_HUMAN_TITLE': 'Agregar una nueva fuente humana',
'SEL_AGE_RANGE': 'Seleccione el rango de edad del participante:',
'AGE_0_6': '3 meses - 6 años',
'AGE_7_12': '7-12 años',
'AGE_13_17': '13-17 años',
'AGE_18': '18+ años',
# TODO: DO NOT MERGE WITHOUT THESE
'PARTICIPATION_AGREEMENT': 'PENDING',
'EXHIBIT_A': 'PENDING',
'BILL_OF_RIGHTS': '''Declaración de derechos del sujeto experimental''',
'TEXT_I_HAVE_READ_1': 'He leído (o alguien me ha leído) este formulario. Soy consciente de que se me pide que participe en un estudio de investigación. Acepto voluntariamente participar en este estudio.',
'TEXT_I_HAVE_READ_SIMPLIFIED': 'Sí, estarás en este estudio de investigación.',
'PERSON_ATTAINING_ASSENT': 'Firma de la persona que obtiene el consentimiento',
'TEXT_ASSENT_WITNESS': 'A mi juicio, el participante está dando su consentimiento voluntaria y conscientemente y posee la capacidad legal de dar su consentimiento para participar en el estudio.',
'OBTAINER_NAME': 'Nombre de la persona que obtiene el consentimiento',
'TEXT_I_HAVE_READ_PARENT': 'He leído (o alguien me ha leído) este formulario. Soy consciente de que se le está pidiendo a mi hijo que participe en un estudio de investigación. Acepto voluntariamente que mi hijo participe en este estudio',
'PARTICIPANT_NAME': 'Nombre del participante',
'PARTICIPANT_EMAIL': 'Correo electrónico del participante',
'PARTICIPANT_PARENT_1': 'Nombre del Padre de Familia / Guardian',
'PARTICIPANT_PARENT_2': 'Nombre del padre / tutor del segundo padre',
'PARTICIPANT_DECEASED_PARENTS': 'Uno de los padres / tutor ha fallecido o no puede dar su consentimiento',
'DATE_SIGNED': 'Fecha firmada',
'PARTICIPANT_ADDRESS': 'Dirección del participante',
'PARTICIPANT_CITY': 'Ciudad participante',
'PARTICIPANT_STATE': 'Estado participante',
'PARTICIPANT_ZIPCODE': 'Código postal del participante',
'PARTICIPANT_COUNTRY': 'País participante',
'CONSENT_YOUR_CHILD': '''
<p align='center'><b>University of California, San Diego</b><br/>
Consentimiento de los padres para que su hijo participe como sujeto en una investigación<br/></p>
<p align='center' style='font-weight: bold;'>Proyecto American Gut</p>
<p style='font-weight: bold;'><i>¿Quién realiza el estudio, por qué se le ha pedido a su hijo que participe, cómo se ha seleccionado a su hijo y cuál es la cifra aproximada de participantes en el estudio?</i></p>
<p>El Dr. Rob Knight está realizando un estudio para saber más sobre los billones de bacterias y otros organismos (denominados “microbioma”) que viven dentro de su cuerpo y en la superficie de este. Usted ha inscrito voluntariamente a su hijo en este estudio porque quiere saber más sobre su microbioma. Los niños, como los demás seres humanos, tienen un microbioma único. Incluirlos en el estudio ayudará a definir el desarrollo del microbioma. En el estudio participarán unas 100 000 personas de todo EE. UU. y de otros países.</p>
<p style='font-weight: bold;'><i>¿Por qué se está llevando a cabo este estudio?</i></p>
<p>El objetivo del estudio es evaluar con mayor precisión las diferencias entre las personas y determinar si dichas diferencias pueden atribuirse al modo de vida, a la dieta, al tipo de constitución corporal, a la edad o a la presencia de enfermedades relacionadas. Los resultados se utilizarán para crear una base de datos que contendrá secuencias y metabolitos de distintas zonas del cuerpo (p. ej., la piel, la boca, el estómago y los intestinos), y detalles del niño participante que provee la muestra. Otros investigadores podrán usar estos datos cuando estén estudiando el mismo tipo de muestra en otros estudios científicos (p. ej., ciertas enfermedades en las que sean comnes las anomalías del estómago y los intestinos). </p>
<p style='font-weight: bold;'>¿Qué le sucederá a su hijo durante el estudio, y qué procedimientos forman parte de la atención estándar y cuáles son experimentales?</p>
<p>Se le pregunta si desea que su hijo participe en este estudio porque usted se registró en el sitio web de American Gut para un análisis microbiológico. Cuando se registró, le enviamos un kit de toma de muestras junto con las instrucciones de inicio de sesión en el sitio web, de modo que pueda dar su consentimiento formal para el estudio.</p>
<p>Analizaremos todas las muestras para las que se hayan completado el formulario de consentimiento y el cuestionario. Se analizarán las muestras suministradas para el proyecto (incluidas las de su hijo) y los resultados se publicarán en artículos científicos en los que se definirá la diversidad del microbioma humano. Se le enviará un enlace a través del que podrá ver, descargar e imprimir diagramas en alta resolución —aptos para enmarcar— de sus resultados y acceder a un informe detallado sobre los taxones encontrados.</p>
<p>A través de este consentimiento, queremos que comprenda lo que haremos con la muestra de su hijo y lo que usted obtendrá a cambio.</p>
<p>Le pediremos que responda un cuestionario en línea sobre el modo de vida y los hábitos alimentarios de su hijo. Calculamos que no deberá llevarle más de 30 minutos. A continuación, tomará una muestra de una parte del cuerpo de su hijo (de interés para usted) con algo semejante a un bastoncillo de algodón estéril frotándolo por la piel o la lengua. También puede tomar una muestra de las heces de una de las siguientes tres formas:</p>
<ol>
<li>Inserte las puntas del bastoncillo en papel higiénico usado y devuelva la muestra en la funda de plástico suministrada.</li>
<li>Inserte las puntas del bastoncillo en papel higiénico usado, pase las puntas por la superficie de una tarjeta para pruebas de sangre oculta en las heces y devuélvanos la tarjeta. La tarjeta para pruebas de sangre oculta en las heces es el mismo instrumento que utiliza el médico para verificar si hay sangre en las heces. La tarjeta para pruebas de sangre oculta en las heces permite estabilizar las heces para su posterior análisis. No verificaremos si hay sangre en las heces con fines diagnósticos, puesto que no somos un laboratorio clínico.</li>
<li>Envíe una muestra completa de heces refrigeradas con hielo (cuando se solicite, para realizar otros análisis) en el recipiente para envíos que le suministraremos. Dicho recipiente contiene una serie de compresas de hielo que enfriarán la muestra de manera fiable a -20 °C/-4 °F.</li>
</ol>
<p>También puede tomar muestras de otras partes del cuerpo, como el oído, la nariz, la vagina, el cuero cabelludo o la planta del pie.</p>
<p>Debe enviarnos los bastoncillos o las tarjetas para pruebas de sangre oculta en las heces en el sobre suministrado y a través del servicio regular de correo nacional. Las muestras de heces completas deben enviarse a los laboratorios Knight Lab en el recipiente para envíos suministrado.</p>
<p>Se extraerá el ADN de la muestra, que se amplificará mediante PCR (reacción en cadena de la polimerasa) y se secuenciará para ver qué bacterias contiene la muestra y en qué proporción. Es posible que utilicemos el resto de la muestra para analizar los metabolitos, como las proteínas, o las sustancias químicas derivadas de las bacterias o para analizar en mayor detalle bacterias específicas que nos resulten de interés. Creemos que tardaremos unos dos meses en conocer los resultados del cálculo inicial de la diversidad bacteriana.</p>
<p>Los resultados se cargarán en su cuenta de American Gut en cuanto estén disponibles.</p>
<p>Le pedimos también que nos autorice a utilizar la muestra de su hijo o el ADN no humano extraído de dicha muestra (p. ej., el ADN de las bacterias) en futuros estudios. Además, queremos solicitarle su consentimiento para ponernos en contacto con usted por correo electrónico para solicitar más información como seguimiento a las preguntas sobre su hijo que haya respondido en el cuestionario.</p>
<p style='font-weight: bold;'>Atención: La secuenciación no tiene fines diagnósticos y no está dirigida al ADN humano.>
<p style='font-weight: bold;'>¿Cuánto tiempo es necesario para realizar cada procedimiento del estudio, cuánto tiempo debe dedicar en total su hijo y cuánto durará el estudio?</p>
<p>Tardará 30 minutos o menos en responder el cuestionario en línea. Tardará 5 minutos o menos en tomar cada una de las muestras que vaya a suministrar. En principio, el estudio durará 5 años. No obstante, los resultados estarán a su disposición antes de que este termine (por lo general, en un plazo de 2 meses después de que recibamos la muestra). Puede optar por tomar muestras de su hijo en más de una ocasión. Si los datos personales de su hijo (p. ej., su dirección o estado de salud) cambian, le pedimos que vuelva a introducir voluntariamente los datos de contacto y/o las respuestas del cuestionario.</p>
<p style='font-weight: bold;'>¿Cuáles son los riesgos relacionados con este estudio?</p>
<p>Las técnicas de toma de muestras se usan desde hace más o menos 10 años y no se han notificado efectos secundarios al respecto. No examinamos el ADN humano que haya en la muestra, por lo que no obtendremos información personal sobre el genoma. Antes de consignar datos en archivos de acceso público se eliminan todos los datos conocidos de la secuencia humana. El personal del estudio ha tomado precauciones para garantizar que el riesgo de pérdida de la confidencialidad sea mínimo. Si se pusiera en riesgo la confidencialidad, las consecuencias para su hijo serían mínimas, pues los resultados no son diagnósticos y no repercuten en la decisión de las aseguradoras de darle o no cobertura a su hijo.</p>
<p><i>(Por lo general, las leyes federales y estatales consideran que es ilegal que las aseguradoras, las aseguradoras para grupos y la mayor parte de los empleadores le discriminen por su información genética. Por norma general, dichas leyes lo protegen de las siguientes formas: a) las aseguradoras y las aseguradoras para grupos no pueden solicitarnos la información genética que obtengamos sobre usted en esta investigación; b) las aseguradoras y las aseguradoras para grupos no pueden usar su información genética para tomar decisiones sobre sus opciones de cobertura o pagos por seguro; c) los empleadores que tengan cinco empleados o más no pueden usar la información genética que obtengamos sobre usted en esta investigación para tomar decisiones de contratación, ascenso o despido ni para definir condiciones laborales.)</i></p>
<p>Dado que este es un estudio de investigación, puede haber riesgos desconocidos que no podemos prever. Le informaremos de cualquier novedad importante al respecto.</p>
<p style='font-weight: bold;'>¿Cuáles son las alternativas a no participar en este estudio?</p>
<p>El estudio es completamente voluntario, y si no permite que su hijo participe no tendrá que hacer frente a ninguna consecuencia. No hay pruebas alternativas.</p>
<p style='font-weight: bold;'>¿Cuáles beneficios podrían anticiparse razonablemente?</p>
<p>Su hijo no obtendrá ningún beneficio directo por participar en este estudio. De cualquier modo, el investigador puede obtener más información sobre el microbioma humano en situaciones de buena salud y de enfermedad, lo que podría resultar valioso para los investigadores de otros estudios.</p>
<p style='font-weight: bold;'>¿Puede decidir que su hijo no participe o se retire del estudio sin recibir sanciones ni perder beneficios?</p>
<p>Ni usted ni su hijo obtendrán ningún beneficio directo por participar en este estudio. Creemos que tal vez sienta curiosidad natural por saber qué bacterias contiene su muestra cómo es en comparación con las muestras de otras personas del mismo sexo y edad. De cualquier modo, el investigador obtendrá más información sobre el microbioma humano en situaciones de buena salud y de enfermedad, lo que podría resultar valioso para los investigadores de otros estudios. Tal vez pueda deducir de sus impuestos la contribución al proyecto. Fundrazr, que se encarga de todas las contribuciones financieras, le enviará un recibo.</p>
<p>Analizaremos todas las muestras para las que se hayan completado el formulario de consentimiento y el cuestionario. Se analizarán las muestras del proyecto (incluidas las de su hijo) y los resultados se publicarán en un artículo científico. Se le enviará un enlace a través del que podrá ver, descargar e imprimir diagramas en alta resolución de sus resultados, aptos para enmarcar, y acceder a un informe detallado sobre los taxones encontrados.</p>
<p>Ni usted ni su médico pueden utilizar los resultados del análisis para confirmar diagnósticos clínicos; no realizamos pruebas de detección de enfermedades infecciosas.</p>
<p style='font-weight: bold;'>¿Se puede retirar a su hijo del estudio sin su consentimiento?</p>
<p>La participación en el estudio es completamente voluntaria. Puede negarse a que su hijo participe o hacer que su hijo se retire del estudio en cualquier momento, sin tener que recibir sanciones ni perder los beneficios que le correspondan. Si decide que no desea que su hijo siga participando en el estudio, se le pedirá que se comunique a la línea de asistencia del proyecto American Gut para comunicarnos su intención de que el niño abandone el estudio. Si no se ha procesado la muestra, puede solicitar un reembolso, que se tramitará en el sitio mediante el que realizó su contribución al proyecto.</p>
<p>Se le notificará cualquier información importante obtenida durante el transcurso del estudio y que pueda afectar a su voluntad de que su hijo siga participando.</p>
<p style='font-weight: bold;'>¿Se le pagará por participar en este estudio?</p>
<p>No recibirá ninguna remuneración económica por participar en este estudio.</p>
<p style='font-weight: bold;'>¿Hay algún gasto vinculado con la participación en el estudio?</p>
<p>Una vez que se haya inscrito en el proyecto y haya enviado por correo su muestra, no tendrá que pagar nada por participar en el estudio.</p>
<p style='font-weight: bold;'>¿Qué sucede si su hijo sufre una lesión como consecuencia directa del estudio?</p>
<p>Si su hijo sufre una lesión como consecuencia directa de su participación en este estudio, la Universidad de California le prestará toda la atención médica necesaria para su tratamiento. Esta universidad no ofrecerá ningún otro tipo de indemnización a su hijo por lesiones. Para saber más sobre este tema, usted o su hijo pueden llamar a la oficina del Programa de protección para investigaciones con seres humanos al 858-246-4777 para consultar sobre sus derechos como sujeto de investigación o denunciar problemas relacionados con el estudio.</p>
<p style='font-weight: bold;'>¿Y la confidencialidad?</p>
<p>Se protegerá la confidencialidad de los registros de la investigación en la medida que lo permita la ley. Todos los datos sobre su hijo que se introduzcan en el sitio web se guardarán en un servidor protegido por contraseña ubicado en el SDSC (San Diego Supercomputer Center), que se encuentra en la UCSD y cuenta con acceso controlado por características biométricas. Los datos financieros de los participantes que contribuyan al proyecto no se pondrán a disposición de los investigadores. El código (que vincula los datos personales del participante con los códigos de barras de las muestras) se guarda en otro servidor protegido por contraseña, al que solo pueden acceder el investigador principal, el investigador secundario, el coordinador de las muestras y los programadores de la base de datos. Todos los análisis se realizan con datos anonimizados; los datos que se consignan en archivos públicos para uso de otros investigadores también se anonimizan. La Junta de Revisión Institucional de la UCSD podrá revisar los registros del estudio.</p>
<p>Tendrá que presentar datos a través de los que se le podría identificar si se publicaran, como su nombre, su edad, su fecha de nacimiento y su dirección. Hemos hecho todo lo posible para garantizar que nadie pueda identificarle a partir de los datos personales que suministre, pero conservamos información fundamental, como su sexo y su edad, sin poner en riesgo sus datos personales ni la integridad de estos.</p>
<p>Es posible que debamos denunciar incidentes confirmados o sospechas razonables de maltrato o abandono de niños, adultos dependientes o personas mayores, incluidos el maltrato físico o emocional, el abuso sexual o económico y el abandono. El único modo en que podríamos descubrir dicho maltrato es que lo denuncie el propio participante o su tutor legal, por lo que no es probable que suceda. Si los investigadores se percatan de este tipo de información, podrán denunciarla ante las autoridades pertinentes.</p>
<p style='font-weight: bold;'>¿A quién puede llamar si tiene alguna duda?</p>
<p>Si tiene alguna duda o problemas relacionados con la investigación, puede llamar a Rob Knight al 858-246-1184 o a Dominic Nguyen al 858-534-8739.</p>
<p>Puede llamar a la oficina del Programa de protección para investigaciones con seres humanos al 858-246-4777 para consultar acerca de sus derechos como sujeto de investigación o denunciar cualquier problema relacionado con el estudio.</p>
<p style='font-weight: bold;'>Firma y consentimiento</p>
<p>Ha recibido una copia de este documento de consentimiento y una copia de la “Declaración de derechos del sujeto experimental”, para que las conserve.</p>
<p>Autoriza a su hijo a participar.</p>''',
'CONSENT_18': '''
<p align='center'><b>University of California, San Diego</b><br/>
Consentimiento para participar como sujeto de investigación</p>
<p style='font-weight: bold;' align='center'>Proyecto American Gut</p>
<p style='font-weight: bold;'><i>¿Quién realiza el estudio, por qué se le ha pedido que participe, cómo fue seleccionado y cuál es la cifra aproximada de participantes en el estudio?</i></p>
<p>El Dr. Rob Knight está realizando un estudio de investigación para saber más sobre los billones de bacterias y otros organismos (denominados “microbioma”) que viven dentro de su cuerpo y en su superficie. Le hemos pedido que participe en este estudio porque posee un microbioma único, distinto al del resto del mundo. En el estudio participarán unas 100 000 personas de todos los EE. UU. y otros países.</p>
<p style='font-weight: bold;'><i>¿Por qué se está llevando a cabo este estudio?</i></p>
<p>El objetivo del estudio es evaluar con mayor precisión las diferencias entre las personas y determinar si dichas diferencias pueden atribuirse al modo de vida, a la dieta, al tipo de constitución corporal, a la edad o a la presencia de enfermedades relacionadas. Los resultados se utilizarán para crear una base de datos que contendrá secuencias y metabolitos de distintas zonas del cuerpo (p. ej., la piel, la boca o el estómago), así como detalles de los participantes que provean las muestras que otros investigadores podrán usar cuando necesiten muestras para compararlas al estudiar el mismo tipo de muestra en otros estudios científicos, p. ej., ciertas enfermedades en las que sean comunes las anomalías del estómago y los intestinos.</p>
<p style='font-weight: bold;'><i>¿Qué le sucederá durante el estudio?</i></p>
<p>Se le ha pedido que participe en este estudio porque se registró en el sitio web de American Gut (estudio sobre el estómago y los intestinos de los estadounidenses) para un análisis microbiológico. Cuando se registró, le enviamos un kit de toma de muestras junto con las instrucciones de inicio de sesión en el sitio web, de modo que pueda dar su consentimiento formal para participar en el estudio.</p>
<p>Analizaremos todas las muestras para las que se hayan completado el formulario de consentimiento y el cuestionario. Se analizarán las muestras suministradas para el proyecto (incluidas las suyas) y los resultados se publicarán en artículos científicos en los que se definirá la diversidad del microbioma humano. Se le enviará un enlace a través del que podrá ver, descargar e imprimir diagramas en alta resolución de sus resultados —aptos para enmarcar— y acceder a un informe más detallado sobre los taxones encontrados. A través de este consentimiento queremos que comprenda lo que haremos con la muestra y lo que usted obtendrá a cambio.</p>
<p>Le pediremos que complete un cuestionario en línea sobre su modo de vida y sus hábitos alimentarios. Calculamos que no deberá llevarle más de 30 minutos. A continuación, le pediremos que tome una muestra de una parte de su cuerpo (de interés para usted) con algo semejante a un bastoncillo de algodón estéril frotándolo por la piel o la lengua. También puede tomar una muestra de sus heces de una de las siguientes tres formas:</p>
<ol>
<li>Inserte las puntas del bastoncillo en papel higiénico usado y devuelva la muestra en la funda de plástico suministrada.</li>
<li>Inserte las puntas del bastoncillo en papel higiénico usado, pase las puntas por la superficie de una tarjeta para pruebas de sangre oculta en las heces y devuélvanos la tarjeta. La tarjeta para pruebas de sangre oculta en las heces es el instrumento que utiliza el médico para verificar si hay sangre en las heces. La tarjeta para pruebas de sangre oculta en las heces permite estabilizar las heces para su posterior análisis. No verificaremos si hay sangre en las heces con fines diagnósticos, puesto que no somos un laboratorio clínico.</li>
<li>Envíe una muestra completa de heces refrigeradas con hielo (cuando se le solicite, para realizar otros análisis) en el recipiente para envíos que le suministraremos. Dicho recipiente contiene una serie de compresas de hielo que enfriarán la muestra de manera fiable a -20 °C/-4 °F.</li>
</ol>
<p>También puede tomar muestras de otras partes del cuerpo, como el oído, la nariz, la vagina, el cuero cabelludo o la planta del pie.</p>
<p>Debe enviarnos los bastoncillos o las tarjetas para pruebas de sangre oculta en las heces en el sobre suministrado a través del servicio regular de correo nacional. Las muestras de heces completas deben enviarse al laboratorio Knight Lab en el recipiente para envíos suministrado. </p>
<p>Se extraerá el ADN de la muestra, y este se amplificará mediante PCR (reacción en cadena de la polimerasa) y se secuenciará para ver qué bacterias contiene la muestra y en qué proporción. Es posible que utilicemos el resto de la muestra para analizar los metabolitos, como las proteínas, o las sustancias químicas derivadas de las bacterias o para tratar de detectar bacterias específicas que nos resulten de interés. Creemos que pasarán dos meses para que usted conozca los resultados del cálculo inicial de la diversidad bacteriana.</p>
<p>Los resultados se cargarán en su cuenta de American Gut en cuanto estén disponibles.</p>
<p>Queremos también que nos autorice a utilizar la muestra suministrada o el ADN no humano extraído de dicha muestra (p. ej., el ADN de las bacterias) en futuros estudios. Además, queremos solicitarle su consentimiento para ponernos en contacto con usted por correo electrónico a fin de pedirle más información como seguimiento a las preguntas que haya respondido en el cuestionario.</p>
<p><b><u>Atención: La secuenciación no tiene fines diagnósticos y no está dirigida al ADN humano.</u></b></p>
<p style='font-weight: bold;'><i>¿Cuánto tiempo es necesario para realizar cada procedimiento del estudio, cuánto tiempo debe dedicar en total y cuánto durará el estudio?</i></p>
<p>Tardará 30 minutos o menos para responder el cuestionario en línea. Tardará 5 minutos o menos en tomar cada una de las muestras que vaya a suministrar. Anticipamos que el estudio dure cinco años. No obstante, los resultados estarán a su disposición antes de que el estudio termine (por lo general, en un plazo de 2 meses después de que recibamos la muestra). Puede optar por tomar muestras en más de una ocasión. Si sus datos personales (p. ej., su dirección o estado de salud) cambian, le pedimos que vuelva a introducir voluntariamente sus datos de contacto y/o las respuestas del cuestionario.</p>
<p style='font-weight: bold;'><i>¿Cuáles son los riesgos relacionados con este estudio?</i></p>
<p>Las técnicas de toma de muestras se usan desde hace más o menos 10 años, y no se han notificado efectos secundarios al respecto. No examinamos el ADN humano que haya en la muestra, por lo que no obtendremos información personal sobre su genoma. Antes de consignar datos en archivos de acceso público se eliminan todos los datos conocidos de la secuencia humana. El personal del estudio ha tomado precauciones para garantizar que el riesgo de pérdida de la confidencialidad sea mínimo. Si se pusiera en riesgo la confidencialidad, las consecuencias para usted serían mínimas, pues los resultados no son diagnósticos y no repercuten en la decisión de las aseguradoras de darle o no cobertura. <i>(Por lo general, las leyes federales y estatales consideran que es ilegal que las aseguradoras, las aseguradoras para grupos y la mayor parte de los empleadores le discriminen por su información genética. Por norma general, dichas leyes lo protegen de las siguientes formas: a) las aseguradoras y las aseguradoras para grupos no pueden solicitarnos la información genética que obtengamos sobre usted en esta investigación; b) las aseguradoras y las aseguradoras para grupos no pueden usar su información genética para tomar decisiones sobre sus opciones de cobertura o pagos por seguro; c) los empleadores que tengan cinco empleados o más no pueden usar la información genética que obtengamos sobre usted en esta investigación para tomar decisiones de contratación, ascenso o despido ni para definir condiciones laborales.)</i></p>
<p>Dado que este es un estudio de investigación, puede haber riesgos desconocidos que no podemos prever. Le informaremos de cualquier novedad importante al respecto.</p>
<p style='font-weight: bold;'><i>¿Cuáles son las alternativas a no participar en este estudio?</i></p>
<p>El estudio es completamente voluntario y si no participa, no tendrá que hacer frente a ninguna consecuencia. No hay pruebas alternativas.</p>
<p style='font-weight: bold;'><i>¿Cuáles podrían ser los beneficios de participar?</i></p>
<p>No obtendrá ningún beneficio directo por participar en este estudio. Creemos que tal vez sienta curiosidad natural por saber qué microbios contiene su muestra y cómo es en comparación con las muestras de otras personas del mismo sexo y edad. De cualquier modo, el investigador obtendrá más información sobre el microbioma humano en situaciones de buena salud y de enfermedad, lo que podría resultar valioso para los investigadores de otros estudios. Tal vez pueda deducir de sus impuestos la contribución al proyecto. Fundrazr, que se encarga de todas las contribuciones financieras, le enviará un recibo.</p>
<p>Analizaremos todas las muestras para las que se hayan completado el formulario de consentimiento y el cuestionario. Se analizarán las muestras suministradas (incluidas las suyas) y los resultados se publicarán en un artículo científico. Se le enviará un enlace a través del que podrá ver, descargar e imprimir diagramas en alta resolución de sus resultados, aptos para enmarcar. Ni usted ni su médico pueden utilizar los resultados del análisis para confirmar diagnósticos clínicos; no realizamos pruebas de detección de enfermedades infecciosas.</p>
<p style='font-weight: bold;'><i>¿Puede decidir no participar o retirarse del estudio sin recibir sanciones ni perder beneficios?</i></p>
<p>La participación en el estudio es completamente voluntaria. Puede negarse a participar o retirarse del estudio en cualquier momento, sin tener que recibir sanciones ni perder los beneficios que le correspondan. Si decide que no desea seguir participando en el estudio, se le pedirá que envíe un mensaje a la dirección de correo electrónico de asistencia del proyecto American Gut para comunicarnos su intención de retirarse del estudio. Si no se ha procesado la muestra, puede solicitar un reembolso, que se tramitará en el sitio en el que realizó su contribución al proyecto.</p>
<p>Se le notificará cualquier información importante obtenida durante el transcurso del estudio y que pueda afectar a su deseo de seguir participando.</p>
<p style='font-weight: bold;'><i>¿Se le puede retirar del estudio sin que usted dé su consentimiento?</i></p>
<p>Es posible que se le retire del estudio si no completa el consentimiento. También se le podría retirar si no sigue las instrucciones que le dé el personal del estudio.</p>
<p style='font-weight: bold;'><i>¿Se le pagará por participar en este estudio?</i></p>
<p>No recibirá ninguna remuneración económica por participar en este estudio.</p>
<p style='font-weight: bold;'><i>¿Hay algún gasto vinculado con la participación en el estudio?</i></p>
<p>Una vez que se haya inscrito en el proyecto y haya enviado por correo su muestra, no tendrá que pagar nada por participar en el estudio.</p>
<p style='font-weight: bold;'><i>¿Qué sucede si sufre una lesión como consecuencia directa del estudio?</i></p>
<p>Si sufre una lesión como consecuencia directa de su participación en este estudio, la Universidad de California le prestará toda la atención médica necesaria para el tratamiento de esas lesiones. Esta universidad no le ofrecerá ningún otro tipo de indemnización por lesiones. Para saber más sobre este tema, llame a la oficina del Programa de protección para investigaciones con seres humanos al (858) 246-4777 para consultar acerca de sus derechos como sujeto de investigación o denunciar cualquier problema relacionado con el estudio.</p>
<p style='font-weight: bold;'><i>¿Y su confidencialidad?</i></p>
<p>Se protegerá la confidencialidad de los registros de la investigación en la medida que lo permita la ley. Todos los datos sobre usted que se introduzcan en el sitio web se guardarán en un servidor protegido por contraseña ubicado en el SDSC (San Diego Supercomputer Center), que se encuentra en la UCSD y cuenta con acceso controlado por características biométricas. Los datos financieros de los participantes que contribuyan al proyecto no se pondrán a disposición de los investigadores. El código (que vincula los datos personales del participante con los códigos de barras de las muestras) se guarda en otro servidor protegido por contraseña, al que solo pueden acceder el investigador principal, el investigador secundario, el coordinador de las muestras, el administrador de TI y los programadores de la base de datos. Todos los análisis se realizan con datos anonimizados; los datos que se consignan en archivos públicos para el uso de otros investigadores también se anonimizan. La Junta de Revisión Institucional de la UCSD podrá revisar los registros del estudio. Tendrá que suministrar datos a través de los que se le podría identificar si se publicaran, como su nombre, su edad, su fecha de nacimiento y su dirección. Hemos hecho todo lo posible para garantizar que nadie pueda identificarle a partir de los datos personales que suministre, pero conservamos información fundamental, como su sexo y su edad, sin poner en riesgo sus datos personales ni la integridad de estos.</p>
<p>Es posible que debamos denunciar incidentes confirmados o sospechas razonables de maltrato o abandono de niños, adultos dependientes o personas mayores, incluidos el maltrato físico o emocional, el abuso sexual o económico y el abandono. El único modo en que podríamos descubrir dicho maltrato es que lo denuncie el propio participante o su tutor legal, por lo que no es probable que suceda. Si los investigadores se percatan de este tipo de información, podrán denunciarla ante las autoridades pertinentes.</p>
<p style='font-weight: bold;'><i>¿A quién puede llamar si tiene alguna duda?</i></p>
<p> Si tiene alguna duda o problemas relacionados con la investigación, puede llamar a Rob Knight al 858-246-1184 o a Dominic Nguyen al 858-534-8739.</p>
<p>Puede llamar a la oficina del Programa de protección para investigaciones con seres humanos al 858-246-4777 para consultar acerca de sus derechos como sujeto de investigación o denunciar cualquier problema relacionado con el estudio.</p>
<p style='font-weight: bold;'><i>Firma y consentimiento</i></p>
<p>Ha recibido una copia de este documento de consentimiento y una copia de la “Declaración de derechos del sujeto experimental” para que las conserve.</p>
<p>Acepta participar.</p>''',
'ASSENT_13_17': '''
<p align='center'>
<b>University of California, San Diego</b><br/>
Asentimiento para participar como sujeto de investigación<br/>
(de 13 a 17 años)
</p>
<p align='center'>
<b>Proyecto American Gut</b>
</p>
<p style='font-weight: bold;'><i>¿Quién realiza el estudio, por qué se te ha pedido que participes, cómo se te ha seleccionado y cuál es la cifra aproximada de participantes en el estudio?</i></p>
<p>El Profesor Rob Knight está llevando a cabo un estudio para saber más sobre el microbioma (microorganismos [seres vivos diminutos, como bacterias] inofensivos o inocuos que viven dentro de tu cuerpo y en la superficie de este). Te hemos invitado a participar en este estudio porque como el resto de los habitantes de este planeta, tú tienes un microbioma único, y mientras más personas de todas las edades estudiemos, mejor podremos comprender cómo nos ayudan o nos perjudican los microorganismos. En el estudio participarán unas 100 000 personas.</p>
<p style='font-weight: bold;'><i>¿Por qué se realiza este estudio?</i></p>
<p>El objetivo del estudio es evaluar con mayor precisión las diferencias entre las personas y determinar si dichas diferencias pueden atribuirse al modo de vida, a la dieta, al tipo constitucional, a la edad o a la presencia de enfermedades relacionadas. Los resultados se utilizarán para crear una base de datos que contendrá secuencias y metabolitos de distintas zonas del cuerpo (p. ej., la piel, la boca o el estómago y los intestinos), y detalles acerca de ti (el participante que provee la muestra) que otros investigadores podrán usar cuando necesiten muestras para compararlas con lo que ellos estén estudiando, p. ej., ciertas enfermedades en las que las anomalías estomacales son comunes.</p>
<p style='font-weight: bold;'><i>¿Qué te sucederá durante estudio y qué procedimientos son de referencia y cuáles son experimentales?</i></p>
<p>Cuando hayas dado tu consentimiento para participar en el estudio, tendrás que completar un cuestionario en línea en el que responderás a preguntas sobre tu cuerpo, edad, peso, estatura y hábitos alimentarios, así como si has tomado antibióticos, si tienes determinadas enfermedades o si tomas suplementos, como vitaminas. A continuación, tendrás que tomar una muestra de tu cuerpo con el bastoncillo que se suministra con el kit del proyecto American Gut (sobre el estómago y los intestinos de los estadounidenses). En el sobre encontrarás unas instrucciones que te indicarán qué debes hacer. La muestra más común es de material fecal (heces). Para tomarla, inserta las puntas del bastoncillo en papel higiénico usado o pasa las puntas por la superficie de la tarjeta (la tarjeta para pruebas de sangre oculta en las heces). También puedes tomar la muestra de cualquier zona de la piel, de la lengua o la boca, de las fosas nasales, de la cera de los oídos o de la vagina. Puede que se te pida que deposites materia fecal en un recipiente de plástico, que debes colocar debajo de la taza del inodoro. Ninguna de estas muestras o investigaciones nos permitirán diagnosticar enfermedades. Tampoco examinaremos nada en tu propio ADN que también pueda encontrarse en la materia fecal, o en la piel o la saliva. Puede que deseemos ponernos en contacto contigo para hacerte más preguntas acerca de la información que tú o tu mamá/papá/tutor hayan suministrado en el cuestionario.</p>
<p style='font-weight: bold;'><i>¿Cuánto tiempo es necesario para realizar los procedimientos del estudio, cuánto tiempo debes dedicar en total y cuánto durará el estudio?</i></p>
<p>Tardarás 30 minutos o menos para responder el cuestionario en línea. Tardarás 5 minutos o menos en tomar cada una de las muestras que vayas a suministrar. En principio, el estudio durará 5 años. No obstante, los resultados estarán a tu disposición antes de que este termine (por lo general, en un plazo de 2 meses después de que recibamos la muestra). Puedes optar por tomar muestras en más de una ocasión. Si tus datos personales (p. ej., tu dirección o estado de salud) cambian, te pedimos que vuelvas a introducir voluntariamente tus datos de contacto o las respuestas del cuestionario para que podamos hacer un seguimiento contigo.</p>
<p style='font-weight: bold;'><i>¿Cuáles son los riesgos relacionados con este estudio?</i></p>
<p>Las técnicas de toma de muestras se usan desde hace unos 5 años y no se han notificado efectos secundarios al respecto. No examinaremos tu información genética personal y la información que divulguemos en archivos de datos públicos no contendrá información genética humana, puesto que dicha información se habrá eliminado previamente. El personal del estudio ha tomado precauciones para garantizar que el riesgo de filtración de tus datos personales sea mínimo. Si se publicaran tus datos, las consecuencias serían mínimas, puesto que las pruebas no pueden usarse para elaborar diagnósticos. $(20)s</p>
<p style='font-weight: bold;'><i>¿Cuáles son las alternativas a no participar en este estudio?</i></p>
<p>No estás obligado a participar. No tendrás que hacer frente a ninguna consecuencia.</p>
<p style='font-weight: bold;'><i>¿Cuáles beneficios podrían anticiparse razonablemente?</i></p>
<p>No obtendrás ningún beneficio directo por participar en este estudio. El investigador publicará un artículo científico para describir lo que encuentre en las muestras del estudio, incluida la tuya, pero no de forma tal que se pueda saber que habla de tu muestra. Los resultados serán muy valiosos para los investigadores de otros estudios. Se te enviará un enlace a través del cual podrás acceder a tus datos. De este modo, tanto tú como tus padres sabran qué hay en tu muestra en comparación con las muestras de otras personas similares a ti (del mismo sexo y edad).</p>
<p style='font-weight: bold;'><i>¿Puedes decidir no participar o retirarte del estudio sin recibir sanciones ni perder beneficios?</i></p>
<p>La participación en el estudio es completamente voluntaria. Puedes negarte a participar o retirarte del estudio en cualquier momento, sin tener que recibir sanciones ni perder los beneficios que te correspondan. Si decides que no deseas seguir participando en el estudio, se te pedirá que envíes un mensaje a la dirección de correo electrónico del proyecto American Gut para comunicarnos tu intención de abandonar el estudio. Se te notificará cualquier información importante obtenida durante el transcurso del estudio y que pueda afectar a tu voluntad para seguir participando.</p>
<p style='font-weight: bold;'><i>¿Se te puede retirar del estudio sin tu consentimiento?</i></p>
<p>Es posible que se te retire del estudio si no completas el formulario de consentimiento. También se te podría retirar si no sigues las instrucciones que te suministre el personal del estudio.</p>
<p style='font-weight: bold;'><i>¿Se te pagará por participar en este estudio?</i></p>
<p>No recibirás ninguna remuneración económica por participar en este estudio.</p>
<p style='font-weight: bold;'><i>¿Qué sucede si te lesionas como consecuencia directa del estudio?</i></p>
<p>Si sufres una lesión o te enfermas como consecuencia directa de este estudio, se te prestará la atención médica que necesites.</p>
<p style='font-weight: bold;'><i>¿Y la confidencialidad?</i></p>
<p>Se protegerá la confidencialidad de los registros de la investigación en la medida que lo permita la ley. Todos los datos que se introduzcan en el sitio web se guardarán en un servidor protegido por contraseña ubicado en el SDSC (San Diego Supercomputer Center), que se encuentra en la UCSD y cuenta con acceso controlado por características biométricas. El código (que indica qué código barras se colocó en tu muestra) se guarda en otro servidor protegido por contraseña, al que solo pueden acceder el prof. Knight, el coordinador de las muestras y los programadores de la base de datos. Los datos que se usan en los análisis no indican quién eres. Guardaremos tus datos en un lugar al que podrán acceder otros investigadores, pero no podrán determinar de ningún modo quién eres a partir de dichos datos; no publicaremos, por ejemplo, tu dirección. La Junta de Revisión Institucional de la UCSD podrá revisar los registros del estudio.</p>
<p style='font-weight: bold;'><i>¿A quién puedes llamar si tienes alguna duda?</i></p>
<p>Si tienes alguna duda o problemas relacionados con la investigación, puedes llamar a Rob Knight al 858-246-1184 o a Dominic Nguyen al 858-534-8739.</p>
<p>Puedes llamar a la oficina del Programa de protección para investigaciones con seres humanos al 858-246-4777 para consultar sobre tus derechos como sujeto de investigación o denunciar problemas relacionados con el estudio.</p>
<p style='font-weight: bold;'><i>Firma y asentimiento</i></p>
<p>Has recibido una copia de esta hoja de asentimiento y una copia de la “Declaración de derechos del sujeto experimental”, que deberás guardar.</p>
<p>Aceptas participar.</p>''',
'ASSENT_7_12': '''
<p align='center'>
<b>University of California, San Diego</b><br/>
Asentimiento para participar como sujeto de investigación<br/>
(de 7 a 12 años)
</p>
<p align='center'>
<b>Proyecto Gut</b>
</p>
<p>El Profesor Rob Knight y su equipo de investigación están realizando un estudio para saber más sobre los billones de diminutos seres vivos, como las bacterias, que viven dentro de tu cuerpo o en la superficie de este. Te preguntan si deseas participar en este estudio porque eres diferente (en buen sentido) de todos los demás, del mismo modo que el resto de las personas son diferentes entre sí.</p>
<p>Si decides participar en este estudio, esto es lo que sucederá:</p>
<p>Les pediremos a ti, a tu mamá o a tu papá que tomen una muestra de alguna parte de tu cuerpo (como la piel o la boca) o de tu materia fecal (tomándola del papel higiénico) con un objeto parecido a dos bastoncillos de algodón. A veces necesitamos más materia fecal, por lo que quizá te pidamos que evacúes en un tazón de plástico que se coloca debajo de la silla del inodoro y recibe la materia fecal. Tu mamá o tu papá nos enviará la materia fecal en el tazón.</p>
<p>A veces los niños no se sienten bien mientras participan en este estudio. Podrías sentir un poco de dolor en el lugar de la piel que se frota con el bastoncillo de algodón. La mayor parte de las personas no sienten este dolor.</p>
<p>Si sientes algo así o cualquier otra cosa, no dejes de decírselo a tu mamá o a tu papá.</p>
<p>No es necesario que participes en este estudio de investigación si no quieres. Nadie se molestará contigo si dices que no. Incluso si ahora dices que sí y cambias de opinión después de empezar a participar, podrás retirarte del estudio y nadie se molestará.</p>
<p>No dejes de hablar con tus padres si tienes alguna duda. Si no te explican bien lo que quieras saber, puedes llamar a Dominic Nguyen para pedirle más información. Su número de teléfono es el 858-534-8739. También hay un sitio web en Internet en que se explican las cosas: .<a href = "https://www.americangut.org">https://www.americangut.org</a></p>''',
}
|
def tw(f,t,st):
for x in range(t):
f.write("\t")
nl = True
if st[-1] == "#":
nl = False
st = st[:-1]
f.write(st)
if nl:
f.write("\n")
def write_property_lua(f, tab, name, value, pref = ""):
tw(f, tab, '%s{ name = "%s",' % (pref, name))
tab = tab + 1
if (type(value)==str):
tw(f, tab, 'value = "%s",' % value)
tw(f, t, 'type = "string",')
elif (type(value)==bool):
if (value):
tw(f, tab, 'value = true,')
else:
tw(f, tab, 'value = false,')
tw(f, t, 'type = "bool",')
elif (type(value)==int):
tw(f, t, 'type = "int",')
tw(f, tab, 'value = %d,' % value)
elif (type(value)==float):
tw(f, t, 'type = "real",')
tw(f, tab, 'value = %f,' % value)
elif (type(value)==dict):
tw(f, t, 'type = "dictionary",')
for x in value:
write_property_lua(f,tab,x,value[x])
elif (isinstance(value,ObjectTree)):
if (not value._resource):
print("ERROR: Not a resource!!")
tw(f, tab-1, "},")
return
tw(f, tab, 'type = "resource",')
tw(f, tab, 'resource_type = "%s",' % value._type)
if (value._res_path!=""):
tw(f, tab, 'path = "%s",' % value._res_path)
else:
tw(f, tab, "value = {")
tab = tab + 1
tw(f, tab, 'type = "%s",' % value._type)
for x in value._properties:
write_property_lua(f,tab,x[0],x[1])
tab = tab - 1
tw(f, tab, "},")
elif (isinstance(value,Color)):
tw(f, tab, 'type = "color",')
tw(f, tab, 'value = { %.20f, %.20f, %.20f, %.20f },' % (value.r, value.g, value.b, value.a))
elif (isinstance(value,Vector3)):
tw(f, tab, 'type = "vector3",')
tw(f, tab, 'value = { %.20f, %.20f, %.20f },' % (value.x, value.y, value.z))
elif (isinstance(value,Quat)):
tw(f, tab, 'type = "quaternion",')
tw(f, tab, 'value = { %.20f, %.20f, %.20f, %.20f },' % (value.x, value.y, value.z, value.w))
elif (isinstance(value,Matrix4x3)): # wtf, blender matrix?
tw(f, tab, 'type = "transform",')
tw(f, tab, 'value = { #')
for i in range(3):
for j in range(3):
f.write("%.20f, " % value.m[j][i])
for i in range(3):
f.write("%.20f, " % value.m[i][3])
f.write("},\n")
elif (type(value)==list):
if (len(value)==0):
tw(f, tab-1, "},")
return
first=value[0]
if (type(first)==int):
tw(f, tab, 'type = "int_array",')
tw(f, tab, 'value = #')
for i in range(len(value)):
f.write("%d, " % value[i])
f.write("},\n")
elif (type(first)==float):
tw(f, tab, 'type = "real_array",')
tw(f, tab, 'value = #')
for i in range(len(value)):
f.write("%.20f, " % value[i])
f.write("},\n")
elif (type(first)==str):
tw(f, tab, 'type = "string_array",')
tw(f, tab, 'value = #')
for i in range(len(value)):
f.write('"%s", ' % value[i])
f.write("},\n")
elif (isinstance(first,Vector3)):
tw(f, tab, 'type = "vector3_array",')
tw(f, tab, 'value = #')
for i in range(len(value)):
f.write("{ %.20f, %.20f, %.20f }, " % (value[i].x, value[i].y, value[i].z))
f.write("},\n")
elif (isinstance(first,Color)):
tw(f, tab, 'type = "color_array",')
tw(f, tab, 'value = #')
for i in range(len(value)):
f.write("{ %.20f, %.20f, %.20f, %.20f }, " % (value[i].r, value[i].g, value[i].b, value[i].a))
f.write("},\n")
elif (type(first)==dict):
tw(f, tab, 'type = "dict_array",')
tw(f, tab, 'value = {')
for i in range(len(value)):
write_property_lua(f,tab+1,str(i+1),value[i])
tw(f, tab, '},')
tw(f, tab-1, "},")
def write_node_lua(f,tab,tree,path):
tw(f, tab, '{ type = "%s",')
if not tree._resource:
tw(f, tab+1, 'meta = {')
write_property_lua(f, tab+3, "name", tree._name)
if path != "":
write_property_lua(f, tab+3, "path", path)
tw(f, tab+1, '},')
tw(f, tab+1, "properties = {,")
for x in tree._properties:
write_property_lua(f,tab+2,x[0],x[1])
tw(f, tab+1, "},")
tw(f, tab, '},')
if (path==""):
path="."
else:
if (path=="."):
path=tree._name
else:
path=path+"/"+tree._name
#path="."
for x in tree._children:
write_node_lua(f,tab,x,path)
def write(tree,fname):
f=open(fname,"wb")
f.write("return = {\n")
f.write('\tmagic = "SCENE",\n')
tab = 1
write_node_lua(f,tab,tree,"")
f.write("}\n\n")
|
fileout = open("requests.sh", "w")
for i in range(1,57):
if i >= 10:
s = "0" + str(i)
else:
s = "00" + str(i)
fileout.write("curl -s -H 'Content-Type: application/json' -H " + '"Authorization: Bearer `gcloud auth print-access-token`"' + " https://speech.googleapis.com/v1/speech:recognize -d" + ''' "{'config': {'encoding':'FLAC','sampleRateHertz': 44100,'languageCode': 'en-US','enableWordTimeOffsets': false},'audio': {'uri':'gs://bamboo-foundation-6245/SPLIT-'''+s+'''.flac'}}" > TEMP/OUT-'''+s+".txt\n")
fileout.close(); |
def define_env(env):
"Definition of the module"
@env.macro
def feedback(title, section, slug):
email_address = f"{section}+{slug}@technotes.jakoubek.net"
md = "\n\n## Feedback / Kontakt\n\n"
md += f"Wenn Sie Fragen oder Anregungen zum Artikel *{title}* haben, senden Sie mir bitte eine E-Mail an: [{email_address}](mailto:{email_address}?subject=[Technotes] {title})"
return md
# def on_post_page_macros(env):
# env.raw_markdown += "{{ feedback(page.meta.title, page.meta.section, page.meta.slug) }}"
# env.raw_markdown += '\n\n## Feedback / Kontakt\n\n'
# env.raw_markdown += 'Wenn Sie Fragen oder Anregungen zum Artikel *' + \
# env.page.title + '* haben ...'
# env.raw_markdown += env.page.abs_url
|
class Solution:
# # Greedy (Accepted), O(n) time, O(1) space
# def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
# plots = len(flowerbed)
# flowerbed.append(0)
# prev = planted = 0
# for i in range(plots):
# if flowerbed[i] == 0:
# if prev == 0 and flowerbed[i+1] == 0:
# planted += 1
# flowerbed[i] = 1
# prev = flowerbed[i]
# return planted >= n
# Greedy (Top Voted), O(n) time, O(1) space
def canPlaceFlowers(self, A: List[int], N: int) -> bool:
for i, x in enumerate(A):
if (not x and (i == 0 or A[i-1] == 0)
and (i == len(A)-1 or A[i+1] == 0)):
N -= 1
A[i] = 1
return N <= 0
|
# PyZ3950_parsetab.py
# This file is automatically generated. Do not edit.
_lr_method = 'SLR'
_lr_signature = '\xfc\xb2\xa8\xb7\xd9\xe7\xad\xba"\xb2Ss\'\xcd\x08\x16'
_lr_action_items = {'QUOTEDVALUE':([18,12,14,0,26,],[1,1,1,1,1,]),'LOGOP':([3,5,20,4,6,27,19,24,25,13,22,1,],[-5,-8,-4,-14,14,14,14,-9,-6,-13,-7,-12,]),'SET':([12,14,0,26,],[10,10,10,10,]),'WORD':([12,14,0,5,18,13,24,4,16,15,1,26,],[4,4,4,13,4,-13,13,-14,22,21,-12,4,]),'$':([2,5,3,7,28,25,13,1,4,6,22,20,24,],[-1,-8,-5,0,-3,-6,-13,-12,-14,-2,-7,-4,-9,]),'SLASH':([21,],[26,]),'ATTRSET':([0,],[8,]),'QUAL':([26,17,14,0,12,],[9,23,9,9,9,]),'COMMA':([23,9,11,],[-11,-10,17,]),'LPAREN':([26,14,0,8,12,],[12,12,12,15,12,]),'RPAREN':([19,3,22,1,25,27,5,13,20,4,24,],[25,-5,-7,-12,-6,28,-8,-13,-4,-14,-9,]),'RELOP':([9,11,23,10,],[-10,18,-11,16,]),}
_lr_action = { }
for _k, _v in _lr_action_items.items():
for _x,_y in zip(_v[0],_v[1]):
_lr_action[(_x,_k)] = _y
del _lr_action_items
_lr_goto_items = {'cclfind_or_attrset':([0,],[2,]),'elements':([12,14,26,0,],[3,20,3,3,]),'val':([12,18,14,26,0,],[5,24,5,5,5,]),'top':([0,],[7,]),'cclfind':([12,0,26,],[19,6,27,]),'quallist':([26,12,14,0,],[11,11,11,11,]),}
_lr_goto = { }
for _k, _v in _lr_goto_items.items():
for _x,_y in zip(_v[0],_v[1]):
_lr_goto[(_x,_k)] = _y
del _lr_goto_items
_lr_productions = [
("S'",1,None,None,None),
('top',1,'p_top','/Users/cjkarr/Desktop/python-z3950-importer/PyZ3950/ccl.py',170),
('cclfind_or_attrset',1,'p_cclfind_or_attrset_1','/Users/cjkarr/Desktop/python-z3950-importer/PyZ3950/ccl.py',174),
('cclfind_or_attrset',6,'p_cclfind_or_attrset_2','/Users/cjkarr/Desktop/python-z3950-importer/PyZ3950/ccl.py',178),
('cclfind',3,'p_ccl_find_1','/Users/cjkarr/Desktop/python-z3950-importer/PyZ3950/ccl.py',182),
('cclfind',1,'p_ccl_find_2','/Users/cjkarr/Desktop/python-z3950-importer/PyZ3950/ccl.py',186),
('elements',3,'p_elements_1','/Users/cjkarr/Desktop/python-z3950-importer/PyZ3950/ccl.py',190),
('elements',3,'p_elements_2','/Users/cjkarr/Desktop/python-z3950-importer/PyZ3950/ccl.py',212),
('elements',1,'p_elements_3','/Users/cjkarr/Desktop/python-z3950-importer/PyZ3950/ccl.py',218),
('elements',3,'p_elements_4','/Users/cjkarr/Desktop/python-z3950-importer/PyZ3950/ccl.py',222),
('quallist',1,'p_quallist_1','/Users/cjkarr/Desktop/python-z3950-importer/PyZ3950/ccl.py',229),
('quallist',3,'p_quallist_2','/Users/cjkarr/Desktop/python-z3950-importer/PyZ3950/ccl.py',233),
('val',1,'p_val_1','/Users/cjkarr/Desktop/python-z3950-importer/PyZ3950/ccl.py',237),
('val',2,'p_val_2','/Users/cjkarr/Desktop/python-z3950-importer/PyZ3950/ccl.py',241),
('val',1,'p_val_3','/Users/cjkarr/Desktop/python-z3950-importer/PyZ3950/ccl.py',245),
]
|
# Copyright (c) 2021 Paweł Piskorz
# Licensed under the MIT License
# See attached LICENSE file
__all__ = ('__title__', '__summary__', '__uri__', '__version_info__',
'__version__', '__author__', '__maintainer__', '__email__',
'__copyright__', '__license__')
__title__ = "CComponentCreator"
__summary__ = "Python package for creating components in C language"
__uri__ = "https://github.com/zxvcv/CComponentCreator"
__version_info__ = type("version_info", (), dict(major=0, minor=0, micro=5,
releaselevel="final", serial=0))
__version__ = "{0.major}.{0.minor}.{0.micro}{1}{2}".format(__version_info__,
dict(alpha="a", beta="b", candidate="rc", final="",
post=".post", dev=".dev")[__version_info__.releaselevel],
__version_info__.serial
if __version_info__.releaselevel != "final" else "")
__author__ = "Pawel Piskorz"
__maintainer__ = "Pawel Piskorz"
__email__ = "[email protected]"
__copyright__ = "Copyright (c) 2021 {0}".format(__author__)
__license__ = "MIT License ; {0}".format(
"https://opensource.org/licenses/MIT") |
#
# PySNMP MIB module RSPAN-MGMT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RSPAN-MGMT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:50:21 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, ValueSizeConstraint, ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint")
dlink_common_mgmt, = mibBuilder.importSymbols("DLINK-ID-REC-MIB", "dlink-common-mgmt")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
MibIdentifier, iso, Counter64, Bits, ModuleIdentity, ObjectIdentity, IpAddress, NotificationType, Unsigned32, Gauge32, Integer32, Counter32, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks = mibBuilder.importSymbols("SNMPv2-SMI", "MibIdentifier", "iso", "Counter64", "Bits", "ModuleIdentity", "ObjectIdentity", "IpAddress", "NotificationType", "Unsigned32", "Gauge32", "Integer32", "Counter32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks")
TextualConvention, DisplayString, RowStatus = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString", "RowStatus")
class VlanId(Integer32):
subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(1, 4094)
class PortList(OctetString):
subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(0, 127)
swRSPANMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 171, 12, 68))
if mibBuilder.loadTexts: swRSPANMIB.setLastUpdated('200807290000Z')
if mibBuilder.loadTexts: swRSPANMIB.setOrganization('D-Link Crop.')
swRSPANCtrl = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 12, 68, 1))
swRSPANInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 12, 68, 2))
swRSPANMgmt = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 12, 68, 3))
swRSPANState = MibScalar((1, 3, 6, 1, 4, 1, 171, 12, 68, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: swRSPANState.setStatus('current')
swRSPANMaxSupportedEntry = MibScalar((1, 3, 6, 1, 4, 1, 171, 12, 68, 2, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly")
if mibBuilder.loadTexts: swRSPANMaxSupportedEntry.setStatus('current')
swRSPANCurrentNumEntries = MibScalar((1, 3, 6, 1, 4, 1, 171, 12, 68, 2, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly")
if mibBuilder.loadTexts: swRSPANCurrentNumEntries.setStatus('current')
swRSPANTable = MibTable((1, 3, 6, 1, 4, 1, 171, 12, 68, 3, 1), )
if mibBuilder.loadTexts: swRSPANTable.setStatus('current')
swRSPANEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 12, 68, 3, 1, 1), ).setIndexNames((0, "RSPAN-MGMT-MIB", "swRSPANVLANID"))
if mibBuilder.loadTexts: swRSPANEntry.setStatus('current')
swRSPANVLANID = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 68, 3, 1, 1, 1), VlanId()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swRSPANVLANID.setStatus('current')
swRSPANSourceIngress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 68, 3, 1, 1, 2), PortList()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: swRSPANSourceIngress.setStatus('current')
swRSPANSourceEgress = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 68, 3, 1, 1, 3), PortList()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: swRSPANSourceEgress.setStatus('current')
swRSPANRedirct = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 68, 3, 1, 1, 4), PortList()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: swRSPANRedirct.setStatus('current')
swRSPANRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 12, 68, 3, 1, 1, 5), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: swRSPANRowStatus.setStatus('current')
mibBuilder.exportSymbols("RSPAN-MGMT-MIB", swRSPANTable=swRSPANTable, PortList=PortList, swRSPANInfo=swRSPANInfo, swRSPANSourceIngress=swRSPANSourceIngress, swRSPANSourceEgress=swRSPANSourceEgress, swRSPANRedirct=swRSPANRedirct, swRSPANMIB=swRSPANMIB, swRSPANEntry=swRSPANEntry, VlanId=VlanId, swRSPANMaxSupportedEntry=swRSPANMaxSupportedEntry, swRSPANState=swRSPANState, swRSPANRowStatus=swRSPANRowStatus, swRSPANVLANID=swRSPANVLANID, swRSPANCurrentNumEntries=swRSPANCurrentNumEntries, swRSPANCtrl=swRSPANCtrl, PYSNMP_MODULE_ID=swRSPANMIB, swRSPANMgmt=swRSPANMgmt)
|
class Node:
def __init__(self, declaration_list):
self.declaration_list = declaration_list
def visit(self):
context = {"type": "program"}
return self.declaration_list.visit(context)
|
"""
Problem Description
The program takes a list from the user and finds the cumulative
sum of a list where the ith element is the sum of the first i+1 elements from the original list.
Problem Solution
1. Declare an empty list and initialise to an empty list.
2. Consider a for loop to accept values for the list.
3. Take the number of elements in the list and store it in a variable.
4. Accept the values into the list using another for loop and insert into the list.
5. Using list comprehension and list slicing, find the cumulative sum of elements in the list.
6. Print the original list and the new list.
7. Exit.
"""
a=[]
n=int(input("Enter the number of elements in list: "))
for i in range(n):
data=int(input(f"Enter elements at position {i}: "))
a.append(data)
print("elements in the list: ",end=" ")
for i in range(n):
print(a[i],end=" ")
print()
b=[sum(a[0:i+1]) for i in range(0,n)]
print(f"The new list is: {b}") |
"""Application deployment configuration parameters."""
PROTOCOL = 'http'
HOSTNAME = 'localhost'
PORT = 6040
|
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 22 11:20:42 2021
@author: Keisha
"""
class Bird:
def intro(self):
print("There are man y types of birds.")
def flight(self):
print("Most of the birds can fly ut some caqnnot.")
class sparrow(Bird):
def flight(self):
print("Sparrows can fly.")
class ostrich(Bird):
def flight(self):
print("Ostriches cannot fly.")
obj_bird = Bird()
obj_spr = sparrow()
obj_ost = ostrich()
obj_bird.intro()
obj_bird.flight()
obj_spr.intro()
obj_spr.flight()
obj_ost.intro()
obj_ost.flight()
|
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def _diameterBTree(self,root):
if not root:
return 0
l = self._diameterBTree(root.left)
r = self._diameterBTree(root.right)
self.ans = max(self.ans,1+l+r)
return 1+max(l,r)
def diameterOfBinaryTree(self, root: TreeNode) -> int:
if not root:
return 0
self.ans = 0
self._diameterBTree(root)
return self.ans-1 |
# Description
# 中文
# English
# Given two integers a and b, an operator, choices:
# +, -, *, /
# Calculate a <operator> b.
# Use switch grammar to solve it
# Have you met this question in a real interview?
# Example
# Example 1:
# Input: a = 1, b = 2, operator = +
# Output: 3
# Explanation:
# return the result of : 1 + 2.
# Example 2:
# Input: a = 10, b = 20, operator = *
# Output: 200
# Explanation:
# return the result of: 10 * 20.
# Example 3:
# Input: a = 3, b = 2, operator = /
# Output: 1
# Explanation:
# return the result of: 3 / 2.
# Example 4:
# Input: a = 10, b = 11, operator = -
# Output: -1
# Explanation:
# return the result of: 10 - 11.
class Calculator:
"""
@param a: An integer
@param operator: A character, +, -, *, /.
@param b: An integer
@return: The result
"""
def calculate(self, a, operator, b):
# write your code here
if operator == '+':
return a + b
if operator == '-':
return a - b
if operator == '*':
return a * b
if operator == '/':
return a // b |
a = 15
b = 10
if a < b :
print("A é menor do que B")
r = a + b
print(f"A soma de {a} + {b} é igual a {r}!")
else :
print("A é maior do que B")
r = a - b
print(f"A subtração de {a} - {b} é igual a {r}!")
codigo_compra = 5111
if codigo_compra == 5222:
print("Compra à vista.")
elif codigo_compra == 5333:
print("Compra à prazo no boleto.")
elif codigo_compra == 5444:
print("Compra à prazo no cartão.")
else:
print("Código não cadastrado") |
class Modification:
def __init__(self):
self.AAs=[]
self.mass=0.0
self.NL={}
self.DI={}
self.factor=1
self.name=""
self.ID=-1
def setAAs(self, newAAlist):
self.AAs=newAAlist
return True
def getAAs(self):
return self.AAs
def setMass(self, newMass):
self.mass=newMass
return True
def getMass(self):
return self.mass
def setNL(self, newNLdict):
self.NL=newNLdict
return True
def getNL(self):
return self.NL
def setDI(self, newDIdict):
self.DI=newDIdict
return True
def getDI(self):
return self.DI
def setName(self, newName):
self.name=newName
return True
def getName(self):
return self.name
def setID(self, newID):
self.ID=str(newID)
return True
def getID(self):
return self.ID
def create(self,nameString,modString,NLstring):#,DIstring):
self.name=nameString
for each in modString.split()[0]: # This will be each AA...
self.AAs.append(each)
self.mass=modString.split()[1]
for each in NLstring.split()[0]:
if each != "-":
self.NL[each]=float(NLstring.split()[1])
#for each in DIstring.split()[0]:
# if each != "-":
# self.DI[each]=float(DIstring.split()[1])
def __str__(self):
return self.ID+"_"+self.name+"_"+str(self.mass)
|
class Node:
def __init__(self,data):
self.data=data
self.next=None
class LinkedList:
def __init__(self):
self.head=None
def append(self,newdata):
new_node=Node(newdata)
if self.head is None:
self.head=new_node
return
temp=self.head
while(temp.next):
temp=temp.next
temp.next=new_node
def first_node_of_loop(self,node):
# finding the position where fast=slow
slow=self.head
fast = self.head
while(True):
slow = slow.next
fast = fast.next.next
if slow==fast:
break
#starting from head move fast & cur_node until they are equal
cur_node=self.head
while(cur_node!=fast):
fast=fast.next
cur_node=cur_node.next
return cur_node
arr = list(map(int,input().split()))
l = LinkedList()
for i in range(lenn(arr)):
l.append(arr[i])
print(l.first_node_of_loop(l.head))
|
"""
AS PYTHON DOESN'T HAVE CONSTANT DECLARATION, THE NEXT METHODS
RETURN THE VALUES WHO NEED CONSTANT BEHAVIOR.
"""
def VGL_SHAPE_NCHANNELS():
return 0
def VGL_SHAPE_WIDTH():
return 1
def VGL_SHAPE_HEIGHT():
return 2
def VGL_SHAPE_LENGTH():
return 3
def VGL_MAX_DIM():
return 10
def VGL_ARR_SHAPE_SIZE():
return VGL_MAX_DIM()+1
def VGL_ARR_CLSTREL_SIZE():
return 256
def VGL_STREL_CUBE():
return 1
def VGL_STREL_CROSS():
return 2
def VGL_STREL_GAUSS():
return 3
def VGL_STREL_MEAN():
return 4
def VGL_IMAGE_3D_IMAGE():
return 0
def VGL_IMAGE_2D_IMAGE():
return 1 |
def simplest_numbers_generator():
"""Simplest Number Generator, yielding only two values - 1 and 2.
Disclaimer: Use it just to trace how next and yield operators works.
This example is not useful in real world!
"""
num = 1
print("Yielding", num)
yield num
num +=1
print("Yielding", num)
yield 2
num +=1
print("Yielding", num)
print("Sory, there is nothing to yield...")
def test_simplest_numbers_generator(test):
"""To test the simplest_numbers_generator, use:
test_simplest_numbers_generator("for")
-- to see the generator behaviour on for loop
test_simplest_numbers_generator("next")
-- to see the generator behaviour on next() call
"""
print_header("Testing simplest_numbers_generator on {}".format(test), "#", 50)
# create num_gen generator
num_gen = simplest_numbers_generator()
# print( num_gen.__dir__() )
if test == "for":
for i in num_gen:
print(i)
elif test == "next":
# ask the num_gen for 2 values:
print( next(num_gen) )
print( next(num_gen) )
# ask num_gen for more values that it can yield
print( next(num_gen) )
def print_header(msg, symbol, width):
"""Summary
Args:
msg (String): the text to be printed
symbol (String): the border symbol
width (Int): the width of printing area
"""
print("\n")
print(symbol*width)
print(symbol+msg.center(width-2)+symbol)
print(symbol*width)
test_simplest_numbers_generator("for")
test_simplest_numbers_generator("next")
|
""" --- What is wrong with this family? --- Simple
You have a list of family relationships between father and son.
Every element on this list has two elements. The first is the
father's name, the second is a son's name. All names in the family
are unique. Check if the family tree is correct. There are
no strangers in the family tree. All connections in the family are natural.
Input: list of lists. Every element has two strings. List
has at least one element
Output: bool. Is family tree correct.
Precondition: 1 <= len(tree) < 100
"""
def my_solution(tree):
ancestor = tree[0][0]
dict_tree = {}
for father, son in tree:
if dict_tree.get(father, None):
dict_tree[father].append(son)
else:
dict_tree[father] = [son, ]
fathers = dict_tree.keys()
sons = [i for s in dict_tree.values() for i in s]
if len(fathers) == 1:
return True
if set(fathers) - {ancestor, } - set(sons):
return False
if len(set(sons)) < len(sons):
return False
for k, v in dict_tree.items():
for f in v:
if k in dict_tree.get(f, []):
return False
return True
def tom_tom_solution(tree):
fathers, sons = zip(*tree)
fathers_set, sons_set = set(fathers), set(sons)
return (all(father != son for father, son in tree) and
len(fathers_set - sons_set) == 1 and
len(sons) == len(sons_set))
|
"""CSP (Constraint Satisfaction Problems) problems and solvers. (Chapter 6)."""
# CLASS FROM https://github.com/aimacode/aima-python/ slightly modified for performance (see tag @modified)
# the proof about performance can be found in the files original_results.txt and modified_results.txt
# @modified: removed unused imports
class CSP:
"""This class describes finite-domain Constraint Satisfaction Problems.
A CSP is specified by the following inputs:
variables A list of variables; each is atomic (e.g. int or string).
domains A dict of {var:[possible_value, ...]} entries.
neighbors A dict of {var:[var,...]} that for each variable lists
the other variables that participate in constraints.
constraints A function f(A, a, B, b) that returns true if neighbors
A, B satisfy the constraint when they have values A=a, B=b
In the textbook and in most mathematical definitions, the
constraints are specified as explicit pairs of allowable values,
but the formulation here is easier to express and more compact for
most cases. (For example, the n-Queens problem can be represented
in O(n) space using this notation, instead of O(N^4) for the
explicit representation.) In terms of describing the CSP as a
problem, that's all there is.
However, the class also supports data structures and methods that help you
solve CSPs by calling a search function on the CSP. Methods and slots are
as follows, where the argument 'a' represents an assignment, which is a
dict of {var:val} entries:
assign(var, val, a) Assign a[var] = val; do other bookkeeping
unassign(var, a) Do del a[var], plus other bookkeeping
nconflicts(var, val, a) Return the number of other variables that
conflict with var=val
curr_domains[var] Slot: remaining consistent values for var
Used by constraint propagation routines.
The following methods are used only by graph_search and tree_search:
actions(state) Return a list of actions
result(state, action) Return a successor of state
goal_test(state) Return true if all constraints satisfied
The following are just for debugging purposes:
nassigns Slot: tracks the number of assignments made
display(a) Print a human-readable representation
"""
# added a variable to save the number of backtracks
# in my opinion it is better to show the backtracks instead of the assignments
def __init__(self, variables, domains, neighbors, constraints):
"""Construct a CSP problem. If variables is empty, it becomes domains.keys()."""
variables = variables or list(domains.keys())
self.variables = variables
self.domains = domains
self.neighbors = neighbors
self.constraints = constraints
self.initial = ()
self.curr_domains = None
self.nassigns = 0
self.n_bt = 0
def assign(self, var, val, assignment):
"""Add {var: val} to assignment; Discard the old value if any."""
assignment[var] = val
self.nassigns += 1
def unassign(self, var, assignment):
"""Remove {var: val} from assignment.
DO NOT call this if you are changing a variable to a new value;
just call assign for that."""
if var in assignment:
del assignment[var]
# @Modified: the original used a recursive function, in my opinion this one looks better
# and is easier to understand
def nconflicts(self, var, val, assignment):
"""Return the number of conflicts var=val has with other variables."""
count = 0
for var2 in self.neighbors.get(var):
val2 = None
if assignment.__contains__(var2):
val2 = assignment[var2]
if val2 is not None and self.constraints(var, val, var2, val2) is False:
count += 1
return count
def display(self, assignment):
"""Show a human-readable representation of the CSP."""
# Subclasses can print in a prettier way, or display with a GUI
print('CSP:', self, 'with assignment:', assignment)
def goal_test(self, state):
"""The goal is to assign all variables, with all constraints satisfied."""
assignment = dict(state)
return (len(assignment) == len(self.variables)
and all(self.nconflicts(variables, assignment[variables], assignment) == 0
for variables in self.variables))
# These are for constraint propagation
def support_pruning(self):
"""Make sure we can prune values from domains. (We want to pay
for this only if we use it.)"""
if self.curr_domains is None:
self.curr_domains = {v: list(self.domains[v]) for v in self.variables}
def suppose(self, var, value):
"""Start accumulating inferences from assuming var=value."""
self.support_pruning()
removals = [(var, a) for a in self.curr_domains[var] if a != value]
self.curr_domains[var] = [value]
return removals
def prune(self, var, value, removals):
"""Rule out var=value."""
self.curr_domains[var].remove(value)
if removals is not None:
removals.append((var, value))
def choices(self, var):
"""Return all values for var that aren't currently ruled out."""
return (self.curr_domains or self.domains)[var]
def restore(self, removals):
"""Undo a supposition and all inferences from it."""
for B, b in removals:
self.curr_domains[B].append(b)
# ______________a________________________________________________________________
# Constraint Propagation with AC-3
def AC3(csp, queue=None, removals=None):
"""[Figure 6.3]"""
if queue is None:
queue = [(Xi, Xk) for Xi in csp.variables for Xk in csp.neighbors[Xi]]
csp.support_pruning()
while queue:
(Xi, Xj) = queue.pop()
if revise(csp, Xi, Xj, removals):
if not csp.curr_domains[Xi]:
return False
for Xk in csp.neighbors[Xi]:
if Xk != Xi:
queue.append((Xk, Xi))
return True
def revise(csp, Xi, Xj, removals):
"""Return true if we remove a value."""
revised = False
for x in csp.curr_domains[Xi][:]:
# If Xi=x conflicts with Xj=y for every possible y, eliminate Xi=x
if all(not csp.constraints(Xi, x, Xj, y) for y in csp.curr_domains[Xj]):
csp.prune(Xi, x, removals)
revised = True
return revised
# ______________________________________________________________________________
# CSP Backtracking Search
# Variable ordering
# @Modified: we just want the first one that haven't been assigned so returning fast is good
def first_unassigned_variable(assignment, csp):
"""The default variable order."""
for var in csp.variables:
if var not in assignment:
return var
# @Modified: the original used a function from util files and was harder to understand,
# it also apparently used 2 for loops: one to find the minimum and
# other one to create a list (and a lambda function)
def mrv(assignment, csp):
"""Minimum-remaining-values heuristic."""
vars_to_check = []
size = []
for v in csp.variables:
if v not in assignment.keys():
vars_to_check.append(v)
size.append(num_legal_values(csp, v, assignment))
return vars_to_check[size.index(min(size))]
# @Modified: the original used a function count and a list, in my opinion it is faster to
# just count with a loop 'for' without calling external functions
def num_legal_values(csp, var, assignment):
if csp.curr_domains:
return len(csp.curr_domains[var])
else:
count = 0
for val in csp.domains[var]:
if csp.nconflicts(var, val, assignment) == 0:
count += 1
return count
# Value ordering
def unordered_domain_values(var, assignment, csp):
"""The default value order."""
return csp.choices(var)
def lcv(var, assignment, csp):
"""Least-constraining-values heuristic."""
return sorted(csp.choices(var),
key=lambda val: csp.nconflicts(var, val, assignment))
# Inference
def no_inference(csp, var, value, assignment, removals):
return True
def forward_checking(csp, var, value, assignment, removals):
"""Prune neighbor values inconsistent with var=value."""
for B in csp.neighbors[var]:
if B not in assignment:
for b in csp.curr_domains[B][:]:
if not csp.constraints(var, value, B, b):
csp.prune(B, b, removals)
if not csp.curr_domains[B]:
return False
return True
def mac(csp, var, value, assignment, removals):
"""Maintain arc consistency."""
return AC3(csp, [(X, var) for X in csp.neighbors[var]], removals)
# The search, proper
# @Modified: we should notice that with MRV it works good since the partial initial state
# leaves some variables with unitary domain so we will start to assign these variables.
# Added csp.n_bt+=1
def backtracking_search(csp,
select_unassigned_variable,
order_domain_values,
inference):
"""[Figure 6.5]"""
def backtrack(assignment):
if len(assignment) == len(csp.variables):
return assignment
var = select_unassigned_variable(assignment, csp)
for value in order_domain_values(var, assignment, csp):
if 0 == csp.nconflicts(var, value, assignment):
csp.assign(var, value, assignment)
removals = csp.suppose(var, value)
if inference(csp, var, value, assignment, removals):
result = backtrack(assignment)
if result is not None:
return result
else:
csp.n_bt += 1
csp.restore(removals)
csp.unassign(var, assignment)
return None
result = backtrack({})
assert result is None or csp.goal_test(result)
return result
def different_values_constraint(A, a, B, b):
"""A constraint saying two neighboring variables must differ in value."""
return a != b
|
class Error(Exception):
message = None
def __str__(self):
return repr(self.message)
class GSLZeroDivision(Error):
message = "GSL encountered zero division"
class GSLFailure(Error):
message = "GSL failed"
class GSLMemoryFailure(Error):
message = "GSL failed to allocate necessary memory"
class EFSMTruncationIndexExceeded(Error):
message = "Index of truncation exceeds permissible range"
class EFSMCompilationError(Error):
message = "Import error, perhaps you forgot to run 'make'?"
class EFSMConvergenceParam(Error):
message = "Could not estimate convergence parameter"
class EFSMMaximumIterationExceeded(Error):
message = "Exceeded maximum number of iterations allowed"
class EFSMFailure(Error):
message = "EFSM failed"
gsl_error_mapping = {
-1: GSLFailure,
8: GSLMemoryFailure,
12: GSLZeroDivision
}
|
"""
Tema: Recursividad y Factoriales.
Curso: Pensamiento computacional.
Plataforma: Platzi.
Profesor: David Aroesti.
Alumno: @edinsonrequena.
"""
def factorial(n):
"""Calcula el factorial de n
n int > 0
returns n!
"""
print(n)
if n == 1:
return 1
return n * factorial(n - 1)
def main():
a = int(input("Escribe un entero: "))
print(factorial(a))
if '__main__' == __name__:
main()
|
# coding=utf-8
class TestTeamcityMessages:
def testPass(self):
pass
def testAssertEqual(self):
assert (True == True)
def testAssertEqualFails(self):
assert 1 == 2
def testAssertFalse(self):
assert False
def testException(self):
raise Exception("some exception")
|
#Elabore um programa que calcule o valor a ser pago por um produto,
# considerando o seu preço normal e condição de pagamento:
#– à vista dinheiro/cheque: 10% de desconto
#– à vista no cartão: 5% de desconto
#– em até 2x no cartão: preço formal
#– 3x ou mais no cartão: 20% de juros
valor = float(input('Digite o valor a ser pago: R$ '))
print('Qual a forma de pagamento?')
op = int(input('1 - à vista dinheiro/cheque - 2 à vista no cartão - 3 2x no cartão - 4 3x ou mais no cartão '))
if op == 1:
v_final = valor * 0.9
elif op == 2:
v_final = valor * 0.95
elif op == 3:
v_final = valor
elif op == 4:
v_final = valor * 1.2
p = int(input('Quantas parcelas? '))
print('Suas parcelas: {} vezes de R$ {:.2f}'.format(p, v_final / p))
else:
print('Opção inválida')
print('O valor final para o seu produto é de: R$ {:.2f}'.format(v_final))
|
volatile = False
log_norm = False
# Maximal sequence length in training data
max_seq_len = 50
'''
Embedding layer
'''
# Size of word embedding of source word and target word
src_wemb_size = 512
trg_wemb_size = 512
'''
Encoder layer
'''
# Size of hidden units in encoder
enc_hid_size = 512
'''
Attention layer
'''
# Size of alignment vector
align_size = 512
'''
Decoder layer
'''
# Size of hidden units in decoder
dec_hid_size = 512
# Size of the output vector
out_size = 512
drop_rate = 0.5
# Directory to save model, test output and validation output
dir_model = 'wmodel'
dir_valid = 'wvalid'
dir_tests = 'wtests'
# Validation data
val_shuffle = True
#val_tst_dir = '/home/wen/3.corpus/allnist_stanfordseg_jiujiu/'
#val_tst_dir = '/home5/wen/2.data/allnist_stanseg/'
#val_tst_dir = '/home5/wen/2.data/segment_allnist_stanseg/'
#val_tst_dir = '/home5/wen/2.data/segment_allnist_stanseg_low/'
#val_tst_dir = '/home5/wen/2.data/mt/nist_data_stanseg/'
val_tst_dir = '/home/wen/3.corpus/mt/nist_data_stanseg/'
#val_tst_dir = '/home/wen/3.corpus/segment_allnist_stanseg/'
#val_tst_dir = '/home/wen/3.corpus/wmt2017/de-en/'
#val_tst_dir = './data/'
#val_prefix = 'wmt17.dev'
val_prefix = 'nist02'
#val_prefix = 'devset1_2.lc'
#val_prefix = 'newstest2014.tc'
val_src_suffix = 'src'
val_ref_suffix = 'ref.plain_'
#val_src_suffix = 'zh'
#val_ref_suffix = 'en'
#val_src_suffix = 'en'
#val_ref_suffix = 'de'
ref_cnt = 4
#tests_prefix = ['nist02', 'nist03', 'nist04', 'nist05', 'nist06', 'nist08', 'wmt17.tst']
tests_prefix = ['nist03', 'nist04', 'nist05', 'nist06', 'nist08']
#tests_prefix = ['data2', 'data3', 'test']
#tests_prefix = ['devset3.lc', '900']
#tests_prefix = ['devset3.lc']
#tests_prefix = ['newstest2015.tc', 'newstest2016.tc', 'newstest2017.tc']
#tests_prefix = None
# Training data
train_shuffle = True
batch_size = 80
sort_k_batches = 20
# Data path
dir_data = 'data/'
train_src = dir_data + 'train.src'
train_trg = dir_data + 'train.trg'
# Dictionary
src_vocab_from = train_src
trg_vocab_from = train_trg
src_dict_size = 30000
trg_dict_size = 30000
src_dict = dir_data + 'src.dict.tcf'
trg_dict = dir_data + 'trg.dict.tcf'
inputs_data = dir_data + 'inputs.pt'
# Training
max_epochs = 30
epoch_shuffle = False
epoch_shuffle_minibatch = 1
small = False
display_freq = 10 if small else 1000
sampling_freq = 100 if small else 5000
sample_size = 5
if_fixed_sampling = False
epoch_eval = False
final_test = False
eval_valid_from = 20 if small else 50000
eval_valid_freq = 50 if small else 20000
save_one_model = True
start_epoch = 1
model_prefix = dir_model + '/model'
best_model = dir_valid + '/best.model.pt' if dir_valid else 'best.model.pt'
# pretrained model
#pre_train = None
pre_train = best_model
fix_pre_params = True
# decoder hype-parameters
search_mode = 1
with_batch = 1
ori_search = 0
beam_size = 10
vocab_norm = 1
len_norm = 1
with_mv = 0
merge_way = 'Y'
avg_att = 0
m_threshold = 100.
ngram = 3
length_norm = 0.
cover_penalty = 0.
# optimizer
'''
Starting learning rate. If adagrad/adadelta/adam is used, then this is the global learning rate.
Recommended settings: sgd = 1, adagrad = 0.1, adadelta = 1, adam = 0.001
'''
opt_mode = 'adadelta'
learning_rate = 1.0
#opt_mode = 'adam'
#learning_rate = 1e-3
#opt_mode = 'sgd'
#learning_rate = 1.
max_grad_norm = 1.0
# Start decaying every epoch after and including this epoch
start_decay_from = None
learning_rate_decay = 0.5
last_valid_bleu = 0.
snip_size = 10
file_tran_dir = 'wexp-gpu-nist03'
laynorm = False
segments = False
seg_val_tst_dir = 'orule_1.7'
# model
enc_rnn_type = 'sru' # rnn, gru, lstm, sru
enc_layer_cnt = 4
dec_rnn_type = 'sru' # rnn, gru, lstm, sru
dec_layer_cnt = 4
with_bpe = False
with_postproc = True
copy_trg_emb = False
# 0: groundhog, 1: rnnsearch, 2: ia, 3: ran, 4: rn, 5: sru, 6: cyknet
model = 4
# convolutional layer
#filter_window_size = [1, 3, 5] # windows size
filter_window_size = [1] # windows size
#filter_feats_size = [32, 64, 96]
filter_feats_size = [96]
mlp_size = 256
# generate BTG tree when decoding
dynamic_cyk_decoding = False
print_att = True
# Scheduled Sampling of Samy bengio's paper
ss_type = 1 # 1: linear decay, 2: exponential decay, 3: inverse sigmoid decay
ss_eps_begin = 1 # set None for no scheduled sampling
ss_eps_end = 1
#ss_decay_rate = 0.005
ss_decay_rate = (ss_eps_begin - ss_eps_end) / 10.
ss_k = 0.98 # k < 1 for exponential decay, k >= 1 for inverse sigmoid decay
# free parameter for self-normalization
# 0 is equivalent to the standard neural network objective function.
self_norm_alpha = None
nonlocal_mode = 'dot' # gaussian, dot, embeddedGaussian
#dec_gpu_id = [1]
#dec_gpu_id = None
gpu_id = [0]
#gpu_id = None
|
# PROBLEM
#
# Now write a program that calculates the minimum fixed monthly payment needed
# in order to pay off a credit card balance within 12 months. By a fixed
# monthly payment, we mean a single number which does not change each month,
# but instead is a constant amount that will be paid each month.
#
# In this problem, we will not be dealing with a minimum monthly payment rate.
#
# The following variables contain values as described below:
# 1. balance - the outstanding balance on the credit card
# 2. annualInterestRate - annual interest rate as a decimal
#
# The program should print out one line: the lowest monthly payment that will
# pay off all debt in under 1 year, for example:
#
# 'Lowest Payment: 180'
#
# Assume that the interest is compounded monthly according to the balance at
# the end of the month (after the payment for that month is made). The monthly
# payment must be a multiple of $10 and is the same for all months. Notice
# that it is possible for the balance to become negative using this payment
# scheme, which is okay.
# For test purposes
balance = 5000
annualInterestRate = 0.18
# SOLUTION
def yearEndBalance(balance, monthlyPayment):
'''
balance: outstanding balance on the credit card (int or float)
monthlyPayment: fixed monthly payment (int or float)
returns: ending balance on the credit card after 12 months (int or float)
'''
for month in range(12):
balance = (balance - monthlyPayment) * (1 + monthlyInterestRate)
return balance
monthlyInterestRate = annualInterestRate / 12.0
monthlyPayment = 10*int(balance/12/10) # Initial guess set as 1/12th of balance
while yearEndBalance(balance, monthlyPayment) > 0:
monthlyPayment += 10
print('Lowest Payment:', monthlyPayment)
|
##Hello World Example
#!/user/bin/env python3
print("Hello", "world!")
|
buttons = {
"brightness up": [9097, 4455, 635, 495, 629, 502, 632, 499, 636, 494, 630, 500, 603, 528, 627, 503, 632, 500, 603, 1628, 599, 1632, 606, 1625, 602, 1627, 600, 530, 604, 1626, 601, 1630, 628, 1603, 603, 529, 606, 525, 599, 532, 602, 530, 604, 528, 607, 524, 599, 532, 603, 528, 606, 1625, 610, 1622, 608, 1624, 603, 1627, 600, 1629, 598, 1630, 597, 1631, 596, 1634, 603],
"brightness down": [9115, 4429, 629, 501, 633, 499, 635, 498, 636, 497, 628, 505, 632, 500, 631, 502, 633, 498, 626, 1610, 627, 1597, 630, 1602, 636, 1595, 631, 501, 634, 1598, 598, 1633, 635, 1595, 601, 1630, 627, 505, 629, 502, 633, 499, 604, 527, 631, 502, 629, 503, 600, 532, 634, 497, 606, 1624, 603, 1627, 600, 1630, 597, 1633, 605, 1624, 603, 1627, 600, 1629, 629],
"off": [9093, 4428, 629, 500, 624, 505, 630, 499, 624, 506, 629, 500, 634, 496, 628, 502, 632, 498, 626, 1603, 625, 1604, 633, 1596, 631, 1598, 629, 500, 624, 1605, 636, 1594, 630, 1599, 628, 503, 631, 1598, 629, 501, 633, 498, 626, 504, 630, 501, 633, 497, 627, 503, 631, 1599, 628, 501, 634, 1596, 631, 1599, 628, 1601, 626, 1603, 625, 1605, 632, 1597, 630],
"on": [9103, 4429, 627, 502, 633, 496, 628, 501, 633, 496, 628, 502, 632, 503, 621, 500, 624, 505, 629, 1599, 628, 1600, 627, 1600, 627, 1601, 626, 502, 633, 1595, 631, 1596, 632, 1596, 631, 1597, 629, 1599, 598, 530, 625, 503, 600, 528, 596, 531, 624, 504, 599, 529, 626, 502, 632, 497, 596, 1631, 596, 1632, 595, 1633, 625, 1603, 604, 1624, 603, 1625, 601],
"red": [9119, 4420, 627, 503, 631, 495, 629, 499, 625, 503, 631, 497, 627, 502, 633, 494, 629, 499, 625, 1602, 626, 1602, 625, 1602, 624, 1603, 624, 503, 631, 1597, 630, 1597, 630, 1596, 631, 497, 627, 500, 623, 1604, 623, 505, 630, 497, 627, 501, 633, 495, 629, 499, 625, 1604, 623, 1605, 632, 497, 627, 1601, 626, 1602, 636, 1592, 624, 1605, 632, 1596, 631],
"green": [9083, 4424, 623, 505, 630, 498, 625, 503, 653, 476, 627, 502, 632, 496, 628, 501, 633, 496, 628, 1600, 627, 1601, 626, 1602, 625, 1602, 625, 504, 630, 1598, 629, 1599, 668, 1560, 627, 1601, 626, 503, 631, 1597, 630, 499, 625, 504, 599, 529, 626, 503, 600, 528, 596, 532, 602, 1626, 632, 496, 597, 1631, 596, 1631, 596, 1631, 597, 1631, 596, 1631, 627],
"blue": [9080, 4457, 631, 499, 625, 505, 598, 530, 604, 525, 599, 531, 604, 525, 630, 498, 605, 524, 600, 1628, 599, 1629, 598, 1630, 597, 1631, 596, 532, 602, 1627, 600, 1629, 598, 1631, 596, 533, 601, 1628, 599, 1631, 596, 533, 601, 528, 596, 533, 602, 531, 592, 533, 602, 1627, 600, 528, 596, 533, 601, 1627, 600, 1629, 598, 1630, 597, 1630, 597, 1631, 596],
"white": [9045, 4456, 601, 526, 598, 530, 605, 524, 600, 528, 596, 532, 602, 526, 598, 530, 604, 523, 601, 1627, 600, 1628, 599, 1629, 598, 1631, 596, 532, 602, 1626, 601, 1627, 600, 1628, 599, 1629, 598, 1629, 598, 1630, 597, 532, 602, 526, 598, 531, 604, 525, 599, 529, 605, 524, 600, 528, 606, 522, 603, 1625, 601, 1627, 600, 1627, 600, 1627, 600, 1628, 599],
"orangered": [9072, 4454, 655, 474, 597, 532, 602, 526, 598, 531, 604, 525, 598, 530, 605, 523, 600, 528, 596, 1632, 595, 1632, 595, 1632, 594, 1633, 594, 534, 601, 1627, 600, 1627, 600, 1628, 599, 530, 604, 526, 598, 530, 604, 1623, 604, 524, 600, 528, 596, 533, 601, 527, 597, 1631, 596, 1632, 605, 1624, 603, 525, 599, 1629, 597, 1631, 596, 1632, 595, 1632, 595],
"mediumseagreen": [9058, 4453, 605, 523, 601, 528, 595, 544, 591, 528, 596, 533, 601, 527, 597, 532, 603, 525, 599, 1629, 598, 1629, 598, 1630, 597, 1630, 596, 533, 602, 1625, 602, 1626, 632, 1595, 601, 1626, 632, 496, 628, 500, 624, 1603, 624, 504, 630, 497, 627, 501, 633, 494, 630, 498, 626, 1601, 626, 1601, 625, 503, 632, 1595, 631, 1597, 630, 1597, 630, 1598, 629],
"duke blue": [9048, 4454, 634, 494, 598, 530, 625, 504, 599, 529, 626, 502, 601, 527, 628, 500, 624, 504, 630, 1597, 630, 1598, 630, 1597, 629, 1599, 628, 500, 624, 1603, 624, 1603, 634, 1594, 633, 495, 629, 1599, 628, 500, 634, 1594, 633, 495, 629, 500, 634, 495, 629, 499, 625, 1603, 634, 494, 634, 1594, 629, 500, 624, 1603, 634, 1594, 633, 1595, 632, 1595, 632],
"flash": [9093, 4425, 601, 527, 629, 499, 625, 503, 631, 497, 596, 532, 602, 526, 598, 530, 605, 523, 600, 1627, 601, 1627, 600, 1627, 600, 1628, 599, 529, 605, 1623, 604, 1624, 603, 1625, 603, 1625, 602, 1626, 601, 526, 598, 1629, 598, 530, 604, 523, 601, 527, 597, 531, 604, 524, 600, 528, 596, 1631, 600, 529, 601, 1626, 601, 1627, 600, 1627, 600, 1628, 599],
"darkorange": [9091, 4425, 601, 528, 596, 533, 643, 486, 597, 532, 602, 527, 597, 532, 602, 527, 597, 532, 602, 1627, 600, 1628, 599, 1630, 597, 1631, 596, 533, 601, 1628, 599, 1629, 598, 1631, 596, 543, 592, 526, 597, 1632, 595, 1633, 605, 524, 600, 528, 596, 533, 601, 527, 597, 1632, 605, 1623, 604, 526, 598, 532, 602, 1629, 598, 1631, 607, 1623, 604, 1626, 601],
"carolina blue": [9086, 4456, 602, 528, 606, 525, 599, 537, 598, 528, 606, 525, 599, 532, 602, 528, 596, 534, 600, 1630, 598, 1632, 608, 1622, 602, 1628, 599, 531, 603, 1627, 600, 1629, 598, 1632, 595, 1634, 604, 524, 600, 1629, 598, 1631, 596, 533, 602, 526, 598, 532, 602, 527, 597, 532, 602, 1627, 600, 529, 605, 524, 600, 1629, 598, 1631, 596, 1633, 605, 1624, 603],
"purple": [9081, 4425, 632, 496, 629, 499, 624, 505, 630, 498, 626, 506, 628, 497, 628, 500, 634, 494, 630, 1599, 628, 1600, 627, 1601, 626, 1604, 623, 503, 632, 1596, 630, 1598, 630, 1598, 629, 499, 625, 1604, 633, 1595, 632, 1596, 631, 498, 626, 502, 632, 496, 628, 501, 633, 1596, 635, 495, 625, 505, 630, 501, 633, 1596, 631, 1597, 630, 1599, 628, 1601, 626],
"strobe": [9081, 4424, 633, 496, 628, 501, 634, 495, 628, 501, 634, 496, 628, 502, 632, 497, 627, 502, 601, 1628, 599, 1630, 597, 1632, 595, 1633, 604, 525, 599, 1630, 597, 1632, 605, 1624, 603, 1626, 601, 1628, 599, 1630, 597, 1632, 605, 524, 600, 529, 595, 533, 602, 527, 596, 533, 602, 527, 597, 531, 603, 526, 598, 1631, 596, 1632, 605, 1624, 603, 1626, 601],
"orange": [9082, 4424, 602, 527, 628, 500, 635, 494, 630, 499, 635, 494, 599, 531, 634, 494, 630, 499, 604, 1625, 634, 1594, 632, 1597, 630, 1598, 629, 500, 635, 1594, 633, 1595, 632, 1597, 630, 498, 626, 503, 632, 497, 627, 502, 632, 1596, 631, 497, 627, 502, 632, 496, 628, 1600, 627, 1601, 626, 1602, 626, 1601, 626, 502, 632, 1597, 630, 1599, 628, 1600, 627],
"lightseagreen": [9084, 4461, 597, 533, 601, 528, 596, 533, 601, 527, 628, 501, 633, 496, 597, 531, 603, 527, 597, 1632, 595, 1634, 624, 1604, 634, 1594, 633, 496, 628, 1600, 626, 1603, 624, 1604, 634, 1595, 632, 498, 605, 525, 599, 531, 634, 1594, 633, 496, 628, 500, 634, 495, 629, 499, 625, 1604, 634, 1594, 643, 1586, 631, 497, 627, 1602, 625, 1603, 624, 1604, 633],
"mediumorchid": [9100, 4455, 603, 528, 606, 525, 599, 532, 602, 529, 606, 525, 599, 532, 602, 529, 606, 525, 599, 1636, 601, 1628, 599, 1631, 596, 1634, 603, 527, 597, 1633, 604, 1625, 602, 1628, 599, 532, 602, 1628, 599, 533, 602, 526, 597, 1633, 605, 526, 598, 533, 601, 530, 605, 1626, 601, 530, 604, 1637, 590, 1631, 607, 524, 600, 1630, 597, 1634, 603, 1628, 602],
"fade": [9084, 4459, 599, 532, 602, 529, 605, 525, 599, 532, 602, 528, 607, 524, 599, 532, 603, 528, 595, 1634, 604, 1626, 600, 1629, 598, 1632, 606, 524, 599, 1631, 596, 1634, 604, 1626, 601, 1629, 598, 1631, 596, 534, 600, 528, 596, 1633, 604, 525, 599, 530, 604, 531, 593, 529, 596, 533, 601, 1628, 599, 1630, 597, 532, 602, 1627, 600, 1629, 630, 1599, 597],
"yellow": [9075, 4432, 625, 503, 631, 497, 627, 502, 632, 496, 628, 500, 634, 494, 630, 498, 625, 503, 632, 1597, 630, 1598, 629, 1600, 596, 1631, 627, 502, 632, 1597, 630, 1599, 628, 1603, 635, 496, 628, 502, 601, 1629, 598, 533, 632, 1599, 597, 534, 632, 500, 634, 497, 606, 1625, 633, 1598, 598, 536, 598, 1629, 598, 543, 591, 1628, 599, 1631, 596, 1633, 604],
"teal": [9089, 4454, 602, 529, 626, 505, 599, 532, 602, 528, 627, 504, 631, 499, 635, 495, 629, 501, 633, 1605, 626, 1598, 626, 1605, 601, 1630, 628, 503, 632, 1599, 628, 1602, 604, 1628, 599, 1632, 626, 505, 598, 1633, 604, 528, 607, 1624, 634, 497, 627, 505, 629, 502, 632, 509, 626, 1595, 631, 499, 646, 1585, 631, 500, 635, 1595, 632, 1598, 629, 1601, 626],
"pink": [9095, 4425, 633, 495, 629, 500, 634, 495, 629, 500, 624, 504, 631, 498, 626, 503, 631, 499, 636, 1595, 632, 1596, 631, 1598, 629, 1599, 628, 501, 633, 1595, 632, 1596, 632, 1597, 599, 528, 596, 1632, 595, 1633, 604, 524, 600, 1627, 600, 528, 596, 531, 604, 524, 600, 1628, 599, 529, 595, 533, 604, 1623, 601, 527, 636, 1592, 596, 1632, 605, 1624, 603],
"smooth": [9078, 4423, 635, 495, 629, 502, 632, 498, 637, 494, 629, 501, 634, 497, 627, 503, 631, 499, 635, 1595, 632, 1598, 629, 1601, 626, 1604, 633, 497, 627, 1602, 625, 1605, 633, 1596, 631, 1598, 628, 1602, 625, 1604, 634, 496, 627, 1602, 625, 504, 631, 498, 636, 494, 630, 500, 634, 496, 628, 502, 633, 1597, 630, 501, 633, 1598, 629, 1601, 627, 1604, 633],
}
colors = {
"red": (255,0,0),
"green": (0,255,0),
"blue": (0,0,255),
"white": (255,255,255),
"orangered": (255,69,0),
"mediumseagreen": (60,179,113),
"duke blue": (0,83,155),
"darkorange": (255,140,0),
"carolina blue": (123,175,233),
"purple": (82,45,128),
"orange": (155,165,0),
"lightseagreen": (32,178,170),
"mediumorchid": (186,85,211),
"yellow": (255,255,0),
"teal": (0,128,128),
"pink": (255, 128, 255),
}
|
# Haystack settings for running tests.
DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = 'haystack_tests.db'
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'haystack',
'core',
]
ROOT_URLCONF = 'core.urls'
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'core.tests.mocks.MockEngine',
},
}
|
def first_method():
"""First sibling package method."""
return 1
def second_method():
"""Second sibling package method."""
return 2
|
"""
https://stackoverflow.com/questions/13650293/understanding-pythons-is-operator
Her tester jeg forskjellen på (is og is not) vs ==
"""
playerOne = {
'name': 'Jørund',
'speciality': 'grit',
'age': 38,
}
shadow = {
'name': 'Jørund',
'speciality': 'grit',
'age': 38,
}
copyCat = playerOne
playerTwo = {
'name': 'Lori',
'speciality': 'thorough',
'age': 36,
}
# print(playerOne == playerTwo)
# print(playerOne == shadow)
# print(playerOne != shadow)
# print(playerOne is not shadow)
# print(playerOne is shadow)
# print(id(playerOne))
# print(id(shadow))
# print (playerOne is copyCat)
print(playerOne['name'])
firstArr = [1,2,3,4]
secondArr = [1,2,3,4]
# print(firstArr is secondArr)
myName = 'Jørund'
yourName = 'Jørund'
# interessant! Strings med samme innhold har samme id
# print(myName == yourName)
# print(myName is yourName) #denne blir lik!
# print(id(myName))
# print(id(yourName))
|
# Python program for implementation of MergeSort(Implement Divide and conquer)
# MergeSort(arr[], l, r)
# If r > l
# 1. Find the middle point to divide the array into two halves:
# middle m = l+ (r-l)/2
# 2. Call mergeSort for first half:
# Call mergeSort(arr, l, m)
# 3. Call mergeSort for second half:
# Call mergeSort(arr, m+1, r)
# 4. Merge the two halves sorted in step 2 and 3:
# Call merge(arr, l, m, r)
def mergeSort(arr):
if len(arr) > 1:
mid = len(arr)//2
L = arr[:mid]
R = arr[mid:]
mergeSort(L)
mergeSort(R)
i = j = k = 0
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
while i < len(L):
arr[k] = L[i]
i += 1
k += 1
while j < len(R):
arr[k] = R[j]
j += 1
k += 1
def printList(arr):
for i in range(len(arr)):
print(arr[i], end=" ")
print()
if __name__ == '__main__':
arr = [12, 11, 13, 5, 6, 7]
print("Given array is", end="\n")
printList(arr)
mergeSort(arr)
print("Sorted array is: ", end="\n")
printList(arr)
# Input:
# Given array is
# 12 11 13 5 6 7
# Output:
# Given array is
# 12 11 13 5 6 7
# Sorted array is:
# 5 6 7 11 12 13
|
# -*- coding: utf-8 -*-
"""Class to represent binary data as hexadecimal."""
class Hexdump(object):
"""Class that defines a hexadecimal representation formatter (hexdump)."""
@classmethod
def _FormatDataLine(cls, data, data_offset, data_size):
"""Formats binary data in a single line of hexadecimal representation.
Args:
data: String containing the binary data.
data_offset: Offset of the data.
data_size: Size of the data.
Returns:
A Unicode string containing a hexadecimal representation of
the binary data.
Raises:
ValueError: if the data offset is out of bounds.
"""
if data_offset < 0 or data_offset >= data_size:
raise ValueError(u'Data offset value out of bounds.')
if data_size - data_offset > 16:
data_size = data_offset + 16
word_values = []
for byte_offset in range(data_offset, data_size, 2):
word_value = u'{0:02x}{1:02x}'.format(
ord(data[byte_offset]), ord(data[byte_offset + 1]))
word_values.append(word_value)
byte_values = []
for byte_offset in range(data_offset, data_size):
byte_value = ord(data[byte_offset])
if byte_value > 31 and byte_value < 127:
byte_value = data[byte_offset]
else:
byte_value = u'.'
byte_values.append(byte_value)
return u'{0:07x}: {1:s} {2:s}'.format(
data_offset, u' '.join(word_values), u''.join(byte_values))
@classmethod
def FormatData(cls, data, data_offset=0, maximum_data_size=None):
"""Formats binary data in hexadecimal representation.
All ASCII characters in the hexadecimal representation (hexdump) are
translated back to their character representation.
Args:
data: String containing the binary data.
data_offset: Optional offset within the data to start formatting.
The default is 0.
maximum_data_size: Optional maximum size of the data to format.
The default is None which represents all of
the binary data.
Returns:
A Unicode string containing a hexadecimal representation of
the binary data.
"""
data_size = len(data)
if maximum_data_size is not None and maximum_data_size < data_size:
data_size = maximum_data_size
output_strings = []
for line_offset in range(data_offset, data_size, 16):
hexdump_line = cls._FormatDataLine(data, line_offset, data_size)
output_strings.append(hexdump_line)
return u'\n'.join(output_strings)
|
class Component(object):
_env = None
_di = None
_args = None
_kwargs = None
def setDi(self, di):
self._di = di
def getDi(self):
return self._di
def getEnv(self):
return self._env
def setEnv(self, env):
self._env = env
def setArgs(self, args):
self._args = args
def getArgs(self):
return self._args
def setKwargs(self,kwargs):
self._kwargs = kwargs
def getKwargs(self):
return self._kwargs
def __init__(self, env, di, args, **kwargs):
self._env = env
self._di = di
self._args = args
self._kwargs = kwargs
def run(self):
raise Exception("implement run in {0}".format(self))
|
with open('F:\\url.txt', 'r') as f:
list1 = f.readlines()
def remain720p(args):
return args.find('720P') > 0
list2 = filter(remain720p, list1)
with open('F:\\url2.txt', 'w') as f2:
for str2 in list2:
f2.writelines(str2) |
"""
This contains emperically derived constants from Hutto and Gilbert (2014)
"""
# (empirically derived mean sentiment intensity rating increase for booster words)
B_INCR = 0.293
B_DECR = -0.293
# (empirically derived mean sentiment intensity rating increase for using ALLCAPs to emphasize a word)
C_INCR = 0.733 # capitatilization scaler
N_SCALAR = -0.74
BEFORE_BUT_SCALAR = 0.5
AFTER_BUT_SCALAR = 1.5 |
# -*- coding: utf-8 -*-
{
'name': "onesphere_assembly_industry",
'summary': """
智能装配行业扩展模块""",
'description': """
智能装配行业扩展模块
""",
'author': "上海文享信息科技有限公司",
'website': "http://www.oneshare.com.cn",
# Categories can be used to filter modules in modules listing
# Check https://github.com/odoo/odoo/blob/14.0/odoo/addons/base/data/ir_module_category_data.xml
# for the full list
'category': 'Manufacturing/Manufacturing',
'version': '14.0.10.1',
# any module necessary for this one to work correctly
'depends': ['onesphere_mdm', 'onesphere_oss', 'web_image_editor', 'onesphere_spc', 'web_echarts'],
# always loaded
'data': [
'security/ir.model.access.csv',
'data/product_data.xml',
'data/maintenance_category_data.xml',
'data/quality_data.xml',
'data/tightening_data.xml',
'data/tightening_vendor_data.xml',
'data/product_category_data.xml',
'data/template_download_data.xml',
'wizards/oneshare_modal.xml',
'wizards/assembly_industry_spc_views.xml',
'views/tightening_result_views.xml',
'views/templates.xml',
'views/tightening_unit_views.xml',
'views/quality_views.xml',
'views/work_step_tag_views.xml',
'views/tightening_bolt_views.xml',
'views/mdm_menu_views.xml',
'views/mrp_routing_workcenter_views.xml',
# 'views/real_oper_version_views.xml',
'views/mrp_bom.xml',
'views/assembly_industry_menuitem.xml',
'views/group_tightening_tool.xml',
'wizards/import_view.xml',
'views/import_menu_views.xml',
],
# only loaded in demonstration mode
'demo': [
'demo/tightening_unit_demo.xml',
'demo/tightening_result_demo.xml',
],
'qweb': [
'static/xml/template.xml',
],
'application': True,
}
|
def fib(i: int) -> int:
if i == 0 or i == 1:
return 1
return fib(i - 1) + fib(i - 2)
if __name__ == "__main__":
# Using a variable to workaround
# https://github.com/adsharma/py2many/issues/64
rv = fib(5)
print(rv)
|
print('===== DESAFIO 42 =====')
l1 = float(input('Digite o comprimento da reta 01: '))
l2 = float(input('Digite o comprimento da reta 02: '))
l3 = float(input('Digite o comprimento da reta 03: '))
tri = (l1 < l2 + l3) and (l2 < l1 + l3) and (l3 < l1 + l2)
if tri is True:
print('As retas podem formar um triângulo!')
else:
print('As retas não podem formar um triângulo!')
if l1 == l2 and l2 == l3:
print('Este triângulo é EQUILÁTERO!')
elif tri is True and (l1 != l2) and (l2 != l3) and (l1 != l3):
print('Este triângulo é ESCALENO')
elif (l1 == l2) or (l1 == l3) or (l2 == l3):
print('Este triângulo é ISÓSCELES')
|
"""Constants for the Shelly integration."""
COAP = "coap"
DATA_CONFIG_ENTRY = "config_entry"
DEVICE = "device"
DOMAIN = "shelly"
REST = "rest"
CONF_COAP_PORT = "coap_port"
DEFAULT_COAP_PORT = 5683
# Used in "_async_update_data" as timeout for polling data from devices.
POLLING_TIMEOUT_SEC = 18
# Refresh interval for REST sensors
REST_SENSORS_UPDATE_INTERVAL = 60
# Timeout used for aioshelly calls
AIOSHELLY_DEVICE_TIMEOUT_SEC = 10
# Multiplier used to calculate the "update_interval" for sleeping devices.
SLEEP_PERIOD_MULTIPLIER = 1.2
# Multiplier used to calculate the "update_interval" for non-sleeping devices.
UPDATE_PERIOD_MULTIPLIER = 2.2
# Shelly Air - Maximum work hours before lamp replacement
SHAIR_MAX_WORK_HOURS = 9000
# Map Shelly input events
INPUTS_EVENTS_DICT = {
"S": "single",
"SS": "double",
"SSS": "triple",
"L": "long",
"SL": "single_long",
"LS": "long_single",
}
# List of battery devices that maintain a permanent WiFi connection
BATTERY_DEVICES_WITH_PERMANENT_CONNECTION = ["SHMOS-01"]
EVENT_SHELLY_CLICK = "shelly.click"
ATTR_CLICK_TYPE = "click_type"
ATTR_CHANNEL = "channel"
ATTR_DEVICE = "device"
CONF_SUBTYPE = "subtype"
BASIC_INPUTS_EVENTS_TYPES = {
"single",
"long",
}
SHBTN_INPUTS_EVENTS_TYPES = {
"single",
"double",
"triple",
"long",
}
SUPPORTED_INPUTS_EVENTS_TYPES = SHIX3_1_INPUTS_EVENTS_TYPES = {
"single",
"double",
"triple",
"long",
"single_long",
"long_single",
}
INPUTS_EVENTS_SUBTYPES = {
"button": 1,
"button1": 1,
"button2": 2,
"button3": 3,
}
SHBTN_MODELS = ["SHBTN-1", "SHBTN-2"]
# Kelvin value for colorTemp
KELVIN_MAX_VALUE = 6500
KELVIN_MIN_VALUE_WHITE = 2700
KELVIN_MIN_VALUE_COLOR = 3000
UPTIME_DEVIATION = 5
|
"""Hass.io const variables."""
ATTR_DISCOVERY = 'discovery'
ATTR_ADDON = 'addon'
ATTR_NAME = 'name'
ATTR_SERVICE = 'service'
ATTR_CONFIG = 'config'
ATTR_UUID = 'uuid'
ATTR_USERNAME = 'username'
ATTR_PASSWORD = 'password'
X_HASSIO = 'X-HASSIO-KEY'
X_HASS_USER_ID = 'X-HASS-USER-ID'
X_HASS_IS_ADMIN = 'X-HASS-IS-ADMIN'
|
#!/usr/bin/env python3
# coding=utf-8
# author: @netmanchris
# -*- coding: utf-8 -*-
"""
This module contains functions for authenticating to the Attelani Brid Air Purifier Device
API.
"""
class BridAuth:
"""
Object to hold the authentication data for the Brid API
Note currently, the Brid API requires no authentication. Auth object is created
to allow for caching of IP address of Brid Device and for future enhancements.
:return An object of class AwairAuth to be passed into other functions to
pass the authentication credentials
"""
def __init__(self, ipaddress):
"""
This class acts as the auth object for the Awair API. The token is available from the
Awair developer website.
:param token: str object which contains the
"""
self.ipaddress = ipaddress
self.headers = {
'Accept': 'application/json', 'Content-Type':
'application/json', 'Accept-encoding': 'application/json'}
|
class Defaults(object):
window_size = 7
hidden_sizes = [300]
hidden_activation = 'relu'
max_vocab_size = 1000000
optimizer = 'sgd' # 'adam'
learning_rate = 0.1 # 1e-4
epochs = 20
iobes = True # Map tags to IOBES on input
max_tokens = None # Max dataset size in tokens
encoding = 'utf-8' # Data encoding
output_drop_prob = 0.0 # Dropout probablility prior to output
token_level_eval = False # Force token-level evaluation
verbosity = 1 # 0=quiet, 1=progress bar, 2=one line per epoch
fixed_wordvecs = False # Don't fine-tune word vectors
word_features = True
batch_size = 50
viterbi = True
# Learning rate multiplier for embeddings. This is a tweak to
# implement faster learning for embeddings compared to other
# layers. As the feature is not yet implemented in Keras master
# (see https://github.com/fchollet/keras/pull/1991), this option
# currently requires the fork https://github.com/spyysalo/keras .
embedding_lr_multiplier = 1.0
|
ATOM_COLORS = {
"C": "#c8c8c8",
"H": "#ffffff",
"N": "#8f8fff",
"S": "#ffc832",
"O": "#f00000",
"F": "#ffff00",
"P": "#ffa500",
"K": "#42f4ee",
"G": "#3f3f3f",
}
CHAIN_COLORS = {
"A": "#320000",
"B": "#8a2be2",
"C": "#ff4500",
"D": "#00bfff",
"E": "#ff00ff",
"F": "#ffff00",
"G": "#4682b4",
"H": "#ffb6c1",
"I": "#a52aaa",
"J": "#ee82ee",
"K": "#75FF33",
"L": "#FFBD33",
"M": "#400040",
"N": "#004000",
"O": "#008080",
"P": "#008080",
"R": "#9c6677",
"S": "#b7c5c8",
}
RESIDUE_COLORS = {
"ALA": "#C8C8C8",
"ARG": "#145AFF",
"ASN": "#00DCDC",
"ASP": "#E60A0A",
"CYS": "#E6E600",
"GLN": "#00DCDC",
"GLU": "#E60A0A",
"GLY": "#EBEBEB",
"HIS": "#8282D2",
"ILE": "#0F820F",
"LEU": "#0F820F",
"LYS": "#145AFF",
"MET": "#E6E600",
"PHE": "#3232AA",
"PRO": "#DC9682",
"SER": "#FA9600",
"THR": "#FA9600",
"TRP": "#B45AB4",
"TYR": "#3232AA",
"VAL": "#0F820F",
"ASX": "#FF69B4",
"GLX": "#FF69B4",
"A": "#A0A0FF",
"DA": "#A0A0FF",
"G": "#FF7070",
"DG": "#FF7070",
"I": "#80FFFF",
"C": "#FF8C4B",
"DC": "#FF8C4B",
"T": "#A0FFA0",
"DT": "#A0FFA0",
"U": "#FF8080",
}
RESIDUE_TYPE_COLORS = {
"hydrophobic": "#00ff80",
"polar": "#ff00bf",
"acidic": "#ff4000",
"basic": "#0040ff",
"aromatic": "#ffff00",
"purine": "#A00042",
"pyrimidine": "#4F4600",
}
AMINO_ACID_CLASSES = {
"hydrophobic": ["GLY", "ALA", "LEU", "ILE", "VAL", "MET", "PRO"],
"polar": ["ASN", "GLN", "SER", "THR", "CYS"],
"acidic": ["ASP", "GLU"],
"basic": ["LYS", "ARG", "HIS"],
"aromatic": ["TRP", "TYR", "PHE"],
"purine": ["A", "G", "DA", "DG"],
"pyrimidine": ["DT", "DC", "U", "I", "C"],
}
def create_mol3d_style(
atoms, visualization_type="stick", color_element="atom", color_scheme=None
):
"""Function to create styles input for Molecule3dViewer
@param atoms
A list of atoms. Each atom should be a dict with keys: 'name', 'residue_name', 'chain'
@param visualization_type
A type of molecule visualization graphic: 'stick' | 'cartoon' | 'sphere'.
@param color_element
Elements to apply color scheme to: 'atom' | 'residue' | 'residue_type' | 'chain'.
@param color_scheme
Color scheme used to style moleule elements.
This should be a dict with keys being names of atoms, residues, residue types or chains,
depending on the value of color_element argument. If no value is provided, default color schemes will be used.
"""
if not visualization_type in ['stick', 'cartoon', 'sphere']:
raise Exception("Invalid argument type: visualization_type. Should be: 'stick' | 'cartoon' | 'sphere'.")
if not color_element in ['atom', 'residue', 'residue_type', 'chain']:
raise Exception("Invalid argument type: color_element. Should be: 'atom' | 'residue' | 'residue_type' | 'chain'.")
if not isinstance(atoms, list):
raise Exception("Invalid argument type: atoms. Should be a list of dict.")
if color_scheme and not isinstance(color_scheme, dict):
raise Exception("Invalid argument type: color_scheme. Should be a dict.")
default_color = '#ABABAB'
if color_scheme is None:
color_scheme = {
'atom': ATOM_COLORS,
'residue': RESIDUE_COLORS,
'residue_type': RESIDUE_TYPE_COLORS,
'chain': CHAIN_COLORS
}[color_element]
if color_element == 'residue_type':
residue_type_colors_map = {}
for aa_class_name, aa_class_members in AMINO_ACID_CLASSES.items():
for aa in aa_class_members:
residue_type_colors_map[aa] = color_scheme.get(aa_class_name, default_color)
color_scheme = residue_type_colors_map
atom_styles = []
for a in atoms:
if color_element == 'atom':
atom_color = color_scheme.get(a['name'], default_color)
if color_element in ['residue', 'residue_type']:
atom_color = color_scheme.get(a['residue_name'], default_color)
if color_element == 'chain':
atom_color = color_scheme.get(a['chain'], default_color)
atom_styles.append({
'visualization_type': visualization_type,
'color': atom_color
})
return atom_styles
|
"""Ubuntu Laptop Monitoring - Django project to display laptop hardware status.
.. moduleauthor:: Alexander Dupuy <[email protected]>
"""
|
class Config:
EPS = 1e-14
RPN_CLOBBER_POSITIVES = False
RPN_NEGATIVE_OVERLAP = 0.3
RPN_POSITIVE_OVERLAP = 0.7
RPN_FG_FRACTION = 0.5
RPN_BATCHSIZE = 300
RPN_BBOX_INSIDE_WEIGHTS = (1.0, 1.0, 1.0, 1.0)
RPN_POSITIVE_WEIGHT = -1.0
RPN_PRE_NMS_TOP_N = 12000
RPN_POST_NMS_TOP_N = 1000
RPN_NMS_THRESH = 0.7
RPN_MIN_SIZE = 8
# origin [11, 16, 23, 33, 48, 68, 97, 139, 198, 283]
ANCHORS_HEIGHT = [23, 33, 48, 68, 97, 139]
|
hps = {
"0351291110650853": {
"ott_len": 35,
"ott_percent": 129,
"ott_bw_up": 111,
"tps_qty_index": 65,
"max_risk_long": 85
},
"0561821341040643": {
"ott_len": 56,
"ott_percent": 182,
"ott_bw_up": 134,
"tps_qty_index": 104,
"max_risk_long": 64
},
"0351291110200403": {
"ott_len": 35,
"ott_percent": 129,
"ott_bw_up": 111,
"tps_qty_index": 20,
"max_risk_long": 40
},
"0572181720720673": {
"ott_len": 57,
"ott_percent": 218,
"ott_bw_up": 172,
"tps_qty_index": 72,
"max_risk_long": 67
},
"0331701430640973": {
"ott_len": 33,
"ott_percent": 170,
"ott_bw_up": 143,
"tps_qty_index": 64,
"max_risk_long": 97
},
"66787357652": {
"ott_len": 66,
"ott_percent": 78,
"ott_bw_up": 73,
"tps_qty_index": 57,
"max_risk_long": 65
},
"0701701490000913": {
"ott_len": 70,
"ott_percent": 170,
"ott_bw_up": 149,
"tps_qty_index": 0,
"max_risk_long": 91
},
"0700781390290673": {
"ott_len": 70,
"ott_percent": 78,
"ott_bw_up": 139,
"tps_qty_index": 29,
"max_risk_long": 67
},
"0601050950650813": {
"ott_len": 60,
"ott_percent": 105,
"ott_bw_up": 95,
"tps_qty_index": 65,
"max_risk_long": 81
},
"0400781490420563": {
"ott_len": 40,
"ott_percent": 78,
"ott_bw_up": 149,
"tps_qty_index": 42,
"max_risk_long": 56
},
"0572181750000913": {
"ott_len": 57,
"ott_percent": 218,
"ott_bw_up": 175,
"tps_qty_index": 0,
"max_risk_long": 91
},
"0281701690020483": {
"ott_len": 28,
"ott_percent": 170,
"ott_bw_up": 169,
"tps_qty_index": 2,
"max_risk_long": 48
},
"0631701340690723": {
"ott_len": 63,
"ott_percent": 170,
"ott_bw_up": 134,
"tps_qty_index": 69,
"max_risk_long": 72
},
"0691581140650703": {
"ott_len": 69,
"ott_percent": 158,
"ott_bw_up": 114,
"tps_qty_index": 65,
"max_risk_long": 70
},
"0450781491120653": {
"ott_len": 45,
"ott_percent": 78,
"ott_bw_up": 149,
"tps_qty_index": 112,
"max_risk_long": 65
},
"0691050980650663": {
"ott_len": 69,
"ott_percent": 105,
"ott_bw_up": 98,
"tps_qty_index": 65,
"max_risk_long": 66
},
"0391701430640973": {
"ott_len": 39,
"ott_percent": 170,
"ott_bw_up": 143,
"tps_qty_index": 64,
"max_risk_long": 97
},
"0331291110650813": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 111,
"tps_qty_index": 65,
"max_risk_long": 81
},
"0351291110200453": {
"ott_len": 35,
"ott_percent": 129,
"ott_bw_up": 111,
"tps_qty_index": 20,
"max_risk_long": 45
},
"0701701380640523": {
"ott_len": 70,
"ott_percent": 170,
"ott_bw_up": 138,
"tps_qty_index": 64,
"max_risk_long": 52
},
"0450781490370653": {
"ott_len": 45,
"ott_percent": 78,
"ott_bw_up": 149,
"tps_qty_index": 37,
"max_risk_long": 65
},
"0521051340690693": {
"ott_len": 52,
"ott_percent": 105,
"ott_bw_up": 134,
"tps_qty_index": 69,
"max_risk_long": 69
},
"66788842652": {
"ott_len": 66,
"ott_percent": 78,
"ott_bw_up": 88,
"tps_qty_index": 42,
"max_risk_long": 65
},
"0640781390420673": {
"ott_len": 64,
"ott_percent": 78,
"ott_bw_up": 139,
"tps_qty_index": 42,
"max_risk_long": 67
},
"0700701120370653": {
"ott_len": 70,
"ott_percent": 70,
"ott_bw_up": 112,
"tps_qty_index": 37,
"max_risk_long": 65
},
"0682181720800673": {
"ott_len": 68,
"ott_percent": 218,
"ott_bw_up": 172,
"tps_qty_index": 80,
"max_risk_long": 67
},
"0311051471100663": {
"ott_len": 31,
"ott_percent": 105,
"ott_bw_up": 147,
"tps_qty_index": 110,
"max_risk_long": 66
},
"0701291110370653": {
"ott_len": 70,
"ott_percent": 129,
"ott_bw_up": 111,
"tps_qty_index": 37,
"max_risk_long": 65
},
"0400781360170653": {
"ott_len": 40,
"ott_percent": 78,
"ott_bw_up": 136,
"tps_qty_index": 17,
"max_risk_long": 65
},
"0682181721120663": {
"ott_len": 68,
"ott_percent": 218,
"ott_bw_up": 172,
"tps_qty_index": 112,
"max_risk_long": 66
},
"0331291490650523": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 149,
"tps_qty_index": 65,
"max_risk_long": 52
},
"0334791750000813": {
"ott_len": 33,
"ott_percent": 479,
"ott_bw_up": 175,
"tps_qty_index": 0,
"max_risk_long": 81
},
"57788850852": {
"ott_len": 57,
"ott_percent": 78,
"ott_bw_up": 88,
"tps_qty_index": 50,
"max_risk_long": 85
},
"0581050990500523": {
"ott_len": 58,
"ott_percent": 105,
"ott_bw_up": 99,
"tps_qty_index": 50,
"max_risk_long": 52
},
"0531701470690723": {
"ott_len": 53,
"ott_percent": 170,
"ott_bw_up": 147,
"tps_qty_index": 69,
"max_risk_long": 72
},
"0541701430841003": {
"ott_len": 54,
"ott_percent": 170,
"ott_bw_up": 143,
"tps_qty_index": 84,
"max_risk_long": 100
},
"57788842712": {
"ott_len": 57,
"ott_percent": 78,
"ott_bw_up": 88,
"tps_qty_index": 42,
"max_risk_long": 71
},
"70709372652": {
"ott_len": 70,
"ott_percent": 70,
"ott_bw_up": 93,
"tps_qty_index": 72,
"max_risk_long": 65
},
"0540971110650593": {
"ott_len": 54,
"ott_percent": 97,
"ott_bw_up": 111,
"tps_qty_index": 65,
"max_risk_long": 59
},
"0331291110610813": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 111,
"tps_qty_index": 61,
"max_risk_long": 81
},
"0311031470410553": {
"ott_len": 31,
"ott_percent": 103,
"ott_bw_up": 147,
"tps_qty_index": 41,
"max_risk_long": 55
},
"0292181721120663": {
"ott_len": 29,
"ott_percent": 218,
"ott_bw_up": 172,
"tps_qty_index": 112,
"max_risk_long": 66
},
"0400781470420563": {
"ott_len": 40,
"ott_percent": 78,
"ott_bw_up": 147,
"tps_qty_index": 42,
"max_risk_long": 56
},
"0541291400650653": {
"ott_len": 54,
"ott_percent": 129,
"ott_bw_up": 140,
"tps_qty_index": 65,
"max_risk_long": 65
},
"0312181721100913": {
"ott_len": 31,
"ott_percent": 218,
"ott_bw_up": 172,
"tps_qty_index": 110,
"max_risk_long": 91
},
"0330781470590493": {
"ott_len": 33,
"ott_percent": 78,
"ott_bw_up": 147,
"tps_qty_index": 59,
"max_risk_long": 49
},
"0400781490170563": {
"ott_len": 40,
"ott_percent": 78,
"ott_bw_up": 149,
"tps_qty_index": 17,
"max_risk_long": 56
},
"40789942562": {
"ott_len": 40,
"ott_percent": 78,
"ott_bw_up": 99,
"tps_qty_index": 42,
"max_risk_long": 56
},
"0701291160370653": {
"ott_len": 70,
"ott_percent": 129,
"ott_bw_up": 116,
"tps_qty_index": 37,
"max_risk_long": 65
},
"0331291170220593": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 117,
"tps_qty_index": 22,
"max_risk_long": 59
},
"0310781471100493": {
"ott_len": 31,
"ott_percent": 78,
"ott_bw_up": 147,
"tps_qty_index": 110,
"max_risk_long": 49
},
"57788872652": {
"ott_len": 57,
"ott_percent": 78,
"ott_bw_up": 88,
"tps_qty_index": 72,
"max_risk_long": 65
},
"0660781240650673": {
"ott_len": 66,
"ott_percent": 78,
"ott_bw_up": 124,
"tps_qty_index": 65,
"max_risk_long": 67
},
"0400781360480653": {
"ott_len": 40,
"ott_percent": 78,
"ott_bw_up": 136,
"tps_qty_index": 48,
"max_risk_long": 65
},
"70788864712": {
"ott_len": 70,
"ott_percent": 78,
"ott_bw_up": 88,
"tps_qty_index": 64,
"max_risk_long": 71
},
"0350781380090653": {
"ott_len": 35,
"ott_percent": 78,
"ott_bw_up": 138,
"tps_qty_index": 9,
"max_risk_long": 65
},
"0331291110410523": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 111,
"tps_qty_index": 41,
"max_risk_long": 52
},
"0331701340470523": {
"ott_len": 33,
"ott_percent": 170,
"ott_bw_up": 134,
"tps_qty_index": 47,
"max_risk_long": 52
},
"0311031470420523": {
"ott_len": 31,
"ott_percent": 103,
"ott_bw_up": 147,
"tps_qty_index": 42,
"max_risk_long": 52
},
"0331051110270913": {
"ott_len": 33,
"ott_percent": 105,
"ott_bw_up": 111,
"tps_qty_index": 27,
"max_risk_long": 91
},
"0682181731120663": {
"ott_len": 68,
"ott_percent": 218,
"ott_bw_up": 173,
"tps_qty_index": 112,
"max_risk_long": 66
},
"0701701340690523": {
"ott_len": 70,
"ott_percent": 170,
"ott_bw_up": 134,
"tps_qty_index": 69,
"max_risk_long": 52
},
"70788872612": {
"ott_len": 70,
"ott_percent": 78,
"ott_bw_up": 88,
"tps_qty_index": 72,
"max_risk_long": 61
},
"0312181721100663": {
"ott_len": 31,
"ott_percent": 218,
"ott_bw_up": 172,
"tps_qty_index": 110,
"max_risk_long": 66
},
"0331291490590523": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 149,
"tps_qty_index": 59,
"max_risk_long": 52
},
"0682181571120663": {
"ott_len": 68,
"ott_percent": 218,
"ott_bw_up": 157,
"tps_qty_index": 112,
"max_risk_long": 66
},
"0550781430310673": {
"ott_len": 55,
"ott_percent": 78,
"ott_bw_up": 143,
"tps_qty_index": 31,
"max_risk_long": 67
},
"48788842652": {
"ott_len": 48,
"ott_percent": 78,
"ott_bw_up": 88,
"tps_qty_index": 42,
"max_risk_long": 65
},
"0581050970270653": {
"ott_len": 58,
"ott_percent": 105,
"ott_bw_up": 97,
"tps_qty_index": 27,
"max_risk_long": 65
},
"0572181390030713": {
"ott_len": 57,
"ott_percent": 218,
"ott_bw_up": 139,
"tps_qty_index": 3,
"max_risk_long": 71
},
"0701701341090523": {
"ott_len": 70,
"ott_percent": 170,
"ott_bw_up": 134,
"tps_qty_index": 109,
"max_risk_long": 52
},
"0331291110610493": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 111,
"tps_qty_index": 61,
"max_risk_long": 49
},
"0420781430420553": {
"ott_len": 42,
"ott_percent": 78,
"ott_bw_up": 143,
"tps_qty_index": 42,
"max_risk_long": 55
},
"0631701380480523": {
"ott_len": 63,
"ott_percent": 170,
"ott_bw_up": 138,
"tps_qty_index": 48,
"max_risk_long": 52
},
"0311291490650523": {
"ott_len": 31,
"ott_percent": 129,
"ott_bw_up": 149,
"tps_qty_index": 65,
"max_risk_long": 52
},
"0330781490890673": {
"ott_len": 33,
"ott_percent": 78,
"ott_bw_up": 149,
"tps_qty_index": 89,
"max_risk_long": 67
},
"0311031470030523": {
"ott_len": 31,
"ott_percent": 103,
"ott_bw_up": 147,
"tps_qty_index": 3,
"max_risk_long": 52
},
"0331291490410793": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 149,
"tps_qty_index": 41,
"max_risk_long": 79
},
"0631701471100913": {
"ott_len": 63,
"ott_percent": 170,
"ott_bw_up": 147,
"tps_qty_index": 110,
"max_risk_long": 91
},
"0321031470840913": {
"ott_len": 32,
"ott_percent": 103,
"ott_bw_up": 147,
"tps_qty_index": 84,
"max_risk_long": 91
},
"0311291160930823": {
"ott_len": 31,
"ott_percent": 129,
"ott_bw_up": 116,
"tps_qty_index": 93,
"max_risk_long": 82
},
"0350781380640523": {
"ott_len": 35,
"ott_percent": 78,
"ott_bw_up": 138,
"tps_qty_index": 64,
"max_risk_long": 52
},
"0590821210640523": {
"ott_len": 59,
"ott_percent": 82,
"ott_bw_up": 121,
"tps_qty_index": 64,
"max_risk_long": 52
},
"0660781110370653": {
"ott_len": 66,
"ott_percent": 78,
"ott_bw_up": 111,
"tps_qty_index": 37,
"max_risk_long": 65
},
"0631291110100523": {
"ott_len": 63,
"ott_percent": 129,
"ott_bw_up": 111,
"tps_qty_index": 10,
"max_risk_long": 52
},
"0701701110370653": {
"ott_len": 70,
"ott_percent": 170,
"ott_bw_up": 111,
"tps_qty_index": 37,
"max_risk_long": 65
},
"0331411470590593": {
"ott_len": 33,
"ott_percent": 141,
"ott_bw_up": 147,
"tps_qty_index": 59,
"max_risk_long": 59
},
"0331291080590793": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 108,
"tps_qty_index": 59,
"max_risk_long": 79
},
"0311411471100543": {
"ott_len": 31,
"ott_percent": 141,
"ott_bw_up": 147,
"tps_qty_index": 110,
"max_risk_long": 54
},
"0311291360170653": {
"ott_len": 31,
"ott_percent": 129,
"ott_bw_up": 136,
"tps_qty_index": 17,
"max_risk_long": 65
},
"0331291490980613": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 149,
"tps_qty_index": 98,
"max_risk_long": 61
},
"0321031490840673": {
"ott_len": 32,
"ott_percent": 103,
"ott_bw_up": 149,
"tps_qty_index": 84,
"max_risk_long": 67
},
"0701701400650653": {
"ott_len": 70,
"ott_percent": 170,
"ott_bw_up": 140,
"tps_qty_index": 65,
"max_risk_long": 65
},
"0321031491100913": {
"ott_len": 32,
"ott_percent": 103,
"ott_bw_up": 149,
"tps_qty_index": 110,
"max_risk_long": 91
},
"0321031240840913": {
"ott_len": 32,
"ott_percent": 103,
"ott_bw_up": 124,
"tps_qty_index": 84,
"max_risk_long": 91
},
"0701291160160823": {
"ott_len": 70,
"ott_percent": 129,
"ott_bw_up": 116,
"tps_qty_index": 16,
"max_risk_long": 82
},
"0681701340690523": {
"ott_len": 68,
"ott_percent": 170,
"ott_bw_up": 134,
"tps_qty_index": 69,
"max_risk_long": 52
},
"0731291110650813": {
"ott_len": 73,
"ott_percent": 129,
"ott_bw_up": 111,
"tps_qty_index": 65,
"max_risk_long": 81
},
"0330781470860523": {
"ott_len": 33,
"ott_percent": 78,
"ott_bw_up": 147,
"tps_qty_index": 86,
"max_risk_long": 52
},
"0331031491100493": {
"ott_len": 33,
"ott_percent": 103,
"ott_bw_up": 149,
"tps_qty_index": 110,
"max_risk_long": 49
},
"0311031471070553": {
"ott_len": 31,
"ott_percent": 103,
"ott_bw_up": 147,
"tps_qty_index": 107,
"max_risk_long": 55
},
"0331701710590653": {
"ott_len": 33,
"ott_percent": 170,
"ott_bw_up": 171,
"tps_qty_index": 59,
"max_risk_long": 65
},
"0701291160930653": {
"ott_len": 70,
"ott_percent": 129,
"ott_bw_up": 116,
"tps_qty_index": 93,
"max_risk_long": 65
},
"0331291490980913": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 149,
"tps_qty_index": 98,
"max_risk_long": 91
},
"0331291710790653": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 171,
"tps_qty_index": 79,
"max_risk_long": 65
},
"0312021470370653": {
"ott_len": 31,
"ott_percent": 202,
"ott_bw_up": 147,
"tps_qty_index": 37,
"max_risk_long": 65
},
"0330781470840673": {
"ott_len": 33,
"ott_percent": 78,
"ott_bw_up": 147,
"tps_qty_index": 84,
"max_risk_long": 67
},
"0331121490940803": {
"ott_len": 33,
"ott_percent": 112,
"ott_bw_up": 149,
"tps_qty_index": 94,
"max_risk_long": 80
},
"0331701380700523": {
"ott_len": 33,
"ott_percent": 170,
"ott_bw_up": 138,
"tps_qty_index": 70,
"max_risk_long": 52
},
"0311571490980603": {
"ott_len": 31,
"ott_percent": 157,
"ott_bw_up": 149,
"tps_qty_index": 98,
"max_risk_long": 60
},
"40788117652": {
"ott_len": 40,
"ott_percent": 78,
"ott_bw_up": 81,
"tps_qty_index": 17,
"max_risk_long": 65
},
"0480781390650613": {
"ott_len": 48,
"ott_percent": 78,
"ott_bw_up": 139,
"tps_qty_index": 65,
"max_risk_long": 61
},
"0321031470840773": {
"ott_len": 32,
"ott_percent": 103,
"ott_bw_up": 147,
"tps_qty_index": 84,
"max_risk_long": 77
},
"0311330940420553": {
"ott_len": 31,
"ott_percent": 133,
"ott_bw_up": 94,
"tps_qty_index": 42,
"max_risk_long": 55
},
"0331291490690523": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 149,
"tps_qty_index": 69,
"max_risk_long": 52
},
"0681291350650663": {
"ott_len": 68,
"ott_percent": 129,
"ott_bw_up": 135,
"tps_qty_index": 65,
"max_risk_long": 66
},
"0331761490860523": {
"ott_len": 33,
"ott_percent": 176,
"ott_bw_up": 149,
"tps_qty_index": 86,
"max_risk_long": 52
},
"0371291110420653": {
"ott_len": 37,
"ott_percent": 129,
"ott_bw_up": 111,
"tps_qty_index": 42,
"max_risk_long": 65
},
"0480781470100613": {
"ott_len": 48,
"ott_percent": 78,
"ott_bw_up": 147,
"tps_qty_index": 10,
"max_risk_long": 61
},
"0331291450690523": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 145,
"tps_qty_index": 69,
"max_risk_long": 52
},
"0330911470840853": {
"ott_len": 33,
"ott_percent": 91,
"ott_bw_up": 147,
"tps_qty_index": 84,
"max_risk_long": 85
},
"0400781040690653": {
"ott_len": 40,
"ott_percent": 78,
"ott_bw_up": 104,
"tps_qty_index": 69,
"max_risk_long": 65
},
"0441031110840693": {
"ott_len": 44,
"ott_percent": 103,
"ott_bw_up": 111,
"tps_qty_index": 84,
"max_risk_long": 69
},
"0330781470770673": {
"ott_len": 33,
"ott_percent": 78,
"ott_bw_up": 147,
"tps_qty_index": 77,
"max_risk_long": 67
},
"0661291100370653": {
"ott_len": 66,
"ott_percent": 129,
"ott_bw_up": 110,
"tps_qty_index": 37,
"max_risk_long": 65
},
"0701701380930653": {
"ott_len": 70,
"ott_percent": 170,
"ott_bw_up": 138,
"tps_qty_index": 93,
"max_risk_long": 65
},
"0331291110560823": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 111,
"tps_qty_index": 56,
"max_risk_long": 82
},
"0501030920420453": {
"ott_len": 50,
"ott_percent": 103,
"ott_bw_up": 92,
"tps_qty_index": 42,
"max_risk_long": 45
},
"0331291490840503": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 149,
"tps_qty_index": 84,
"max_risk_long": 50
},
"0331701340690523": {
"ott_len": 33,
"ott_percent": 170,
"ott_bw_up": 134,
"tps_qty_index": 69,
"max_risk_long": 52
},
"0331031471100493": {
"ott_len": 33,
"ott_percent": 103,
"ott_bw_up": 147,
"tps_qty_index": 110,
"max_risk_long": 49
},
"68788818492": {
"ott_len": 68,
"ott_percent": 78,
"ott_bw_up": 88,
"tps_qty_index": 18,
"max_risk_long": 49
},
"0311031471100553": {
"ott_len": 31,
"ott_percent": 103,
"ott_bw_up": 147,
"tps_qty_index": 110,
"max_risk_long": 55
},
"0331701380640523": {
"ott_len": 33,
"ott_percent": 170,
"ott_bw_up": 138,
"tps_qty_index": 64,
"max_risk_long": 52
},
"0701701380570523": {
"ott_len": 70,
"ott_percent": 170,
"ott_bw_up": 138,
"tps_qty_index": 57,
"max_risk_long": 52
},
"0621291110650913": {
"ott_len": 62,
"ott_percent": 129,
"ott_bw_up": 111,
"tps_qty_index": 65,
"max_risk_long": 91
},
"0350781340640523": {
"ott_len": 35,
"ott_percent": 78,
"ott_bw_up": 134,
"tps_qty_index": 64,
"max_risk_long": 52
},
"0311291471100653": {
"ott_len": 31,
"ott_percent": 129,
"ott_bw_up": 147,
"tps_qty_index": 110,
"max_risk_long": 65
},
"0311701350380933": {
"ott_len": 31,
"ott_percent": 170,
"ott_bw_up": 135,
"tps_qty_index": 38,
"max_risk_long": 93
},
"0311030880720553": {
"ott_len": 31,
"ott_percent": 103,
"ott_bw_up": 88,
"tps_qty_index": 72,
"max_risk_long": 55
},
"0331701490640523": {
"ott_len": 33,
"ott_percent": 170,
"ott_bw_up": 149,
"tps_qty_index": 64,
"max_risk_long": 52
},
"66788884672": {
"ott_len": 66,
"ott_percent": 78,
"ott_bw_up": 88,
"tps_qty_index": 84,
"max_risk_long": 67
},
"0331291050940523": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 105,
"tps_qty_index": 94,
"max_risk_long": 52
},
"0400781470690653": {
"ott_len": 40,
"ott_percent": 78,
"ott_bw_up": 147,
"tps_qty_index": 69,
"max_risk_long": 65
},
"0321031481100913": {
"ott_len": 32,
"ott_percent": 103,
"ott_bw_up": 148,
"tps_qty_index": 110,
"max_risk_long": 91
},
"0311031470420653": {
"ott_len": 31,
"ott_percent": 103,
"ott_bw_up": 147,
"tps_qty_index": 42,
"max_risk_long": 65
},
"0331291080420793": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 108,
"tps_qty_index": 42,
"max_risk_long": 79
},
"0331291470690523": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 147,
"tps_qty_index": 69,
"max_risk_long": 52
},
"0331291490110653": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 149,
"tps_qty_index": 11,
"max_risk_long": 65
},
"0701701380570653": {
"ott_len": 70,
"ott_percent": 170,
"ott_bw_up": 138,
"tps_qty_index": 57,
"max_risk_long": 65
},
"0331561340640863": {
"ott_len": 33,
"ott_percent": 156,
"ott_bw_up": 134,
"tps_qty_index": 64,
"max_risk_long": 86
},
"0330781490650503": {
"ott_len": 33,
"ott_percent": 78,
"ott_bw_up": 149,
"tps_qty_index": 65,
"max_risk_long": 50
},
"0311030880400553": {
"ott_len": 31,
"ott_percent": 103,
"ott_bw_up": 88,
"tps_qty_index": 40,
"max_risk_long": 55
},
"0330781470690493": {
"ott_len": 33,
"ott_percent": 78,
"ott_bw_up": 147,
"tps_qty_index": 69,
"max_risk_long": 49
},
"0321031490980913": {
"ott_len": 32,
"ott_percent": 103,
"ott_bw_up": 149,
"tps_qty_index": 98,
"max_risk_long": 91
},
"0321031491100523": {
"ott_len": 32,
"ott_percent": 103,
"ott_bw_up": 149,
"tps_qty_index": 110,
"max_risk_long": 52
},
"0331701490590653": {
"ott_len": 33,
"ott_percent": 170,
"ott_bw_up": 149,
"tps_qty_index": 59,
"max_risk_long": 65
},
"0331291490770553": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 149,
"tps_qty_index": 77,
"max_risk_long": 55
},
"0291291160930583": {
"ott_len": 29,
"ott_percent": 129,
"ott_bw_up": 116,
"tps_qty_index": 93,
"max_risk_long": 58
},
"0341291471100663": {
"ott_len": 34,
"ott_percent": 129,
"ott_bw_up": 147,
"tps_qty_index": 110,
"max_risk_long": 66
},
"0701701380370653": {
"ott_len": 70,
"ott_percent": 170,
"ott_bw_up": 138,
"tps_qty_index": 37,
"max_risk_long": 65
},
"0331291491100613": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 149,
"tps_qty_index": 110,
"max_risk_long": 61
},
"33788842652": {
"ott_len": 33,
"ott_percent": 78,
"ott_bw_up": 88,
"tps_qty_index": 42,
"max_risk_long": 65
},
"0331291490410673": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 149,
"tps_qty_index": 41,
"max_risk_long": 67
},
"0331291490590653": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 149,
"tps_qty_index": 59,
"max_risk_long": 65
},
"70788872532": {
"ott_len": 70,
"ott_percent": 78,
"ott_bw_up": 88,
"tps_qty_index": 72,
"max_risk_long": 53
},
"0701701380840653": {
"ott_len": 70,
"ott_percent": 170,
"ott_bw_up": 138,
"tps_qty_index": 84,
"max_risk_long": 65
},
"39788977342": {
"ott_len": 39,
"ott_percent": 78,
"ott_bw_up": 89,
"tps_qty_index": 77,
"max_risk_long": 34
},
"68788856442": {
"ott_len": 68,
"ott_percent": 78,
"ott_bw_up": 88,
"tps_qty_index": 56,
"max_risk_long": 44
},
"0331271710570653": {
"ott_len": 33,
"ott_percent": 127,
"ott_bw_up": 171,
"tps_qty_index": 57,
"max_risk_long": 65
},
"68788872652": {
"ott_len": 68,
"ott_percent": 78,
"ott_bw_up": 88,
"tps_qty_index": 72,
"max_risk_long": 65
},
"0331531490660793": {
"ott_len": 33,
"ott_percent": 153,
"ott_bw_up": 149,
"tps_qty_index": 66,
"max_risk_long": 79
},
"0331291470650453": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 147,
"tps_qty_index": 65,
"max_risk_long": 45
},
"0330781471040523": {
"ott_len": 33,
"ott_percent": 78,
"ott_bw_up": 147,
"tps_qty_index": 104,
"max_risk_long": 52
},
"0701291161100653": {
"ott_len": 70,
"ott_percent": 129,
"ott_bw_up": 116,
"tps_qty_index": 110,
"max_risk_long": 65
},
"0310781471100523": {
"ott_len": 31,
"ott_percent": 78,
"ott_bw_up": 147,
"tps_qty_index": 110,
"max_risk_long": 52
},
"33788841792": {
"ott_len": 33,
"ott_percent": 78,
"ott_bw_up": 88,
"tps_qty_index": 41,
"max_risk_long": 79
},
"0321291160930523": {
"ott_len": 32,
"ott_percent": 129,
"ott_bw_up": 116,
"tps_qty_index": 93,
"max_risk_long": 52
},
"0331291490110503": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 149,
"tps_qty_index": 11,
"max_risk_long": 50
},
"0331291071100613": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 107,
"tps_qty_index": 110,
"max_risk_long": 61
},
"0701701381100523": {
"ott_len": 70,
"ott_percent": 170,
"ott_bw_up": 138,
"tps_qty_index": 110,
"max_risk_long": 52
},
"0680781090180743": {
"ott_len": 68,
"ott_percent": 78,
"ott_bw_up": 109,
"tps_qty_index": 18,
"max_risk_long": 74
},
"0651291490650523": {
"ott_len": 65,
"ott_percent": 129,
"ott_bw_up": 149,
"tps_qty_index": 65,
"max_risk_long": 52
},
"0331701491100883": {
"ott_len": 33,
"ott_percent": 170,
"ott_bw_up": 149,
"tps_qty_index": 110,
"max_risk_long": 88
},
"0330781490640663": {
"ott_len": 33,
"ott_percent": 78,
"ott_bw_up": 149,
"tps_qty_index": 64,
"max_risk_long": 66
},
"0701701380840573": {
"ott_len": 70,
"ott_percent": 170,
"ott_bw_up": 138,
"tps_qty_index": 84,
"max_risk_long": 57
},
"0331291471100663": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 147,
"tps_qty_index": 110,
"max_risk_long": 66
},
"68788818982": {
"ott_len": 68,
"ott_percent": 78,
"ott_bw_up": 88,
"tps_qty_index": 18,
"max_risk_long": 98
},
"0331291710770653": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 171,
"tps_qty_index": 77,
"max_risk_long": 65
},
"0331701710110653": {
"ott_len": 33,
"ott_percent": 170,
"ott_bw_up": 171,
"tps_qty_index": 11,
"max_risk_long": 65
},
"0310941471100553": {
"ott_len": 31,
"ott_percent": 94,
"ott_bw_up": 147,
"tps_qty_index": 110,
"max_risk_long": 55
},
"0321031470770553": {
"ott_len": 32,
"ott_percent": 103,
"ott_bw_up": 147,
"tps_qty_index": 77,
"max_risk_long": 55
},
"0321031491060503": {
"ott_len": 32,
"ott_percent": 103,
"ott_bw_up": 149,
"tps_qty_index": 106,
"max_risk_long": 50
},
"0680780881100493": {
"ott_len": 68,
"ott_percent": 78,
"ott_bw_up": 88,
"tps_qty_index": 110,
"max_risk_long": 49
},
"0331291491100793": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 149,
"tps_qty_index": 110,
"max_risk_long": 79
},
"0331031471060643": {
"ott_len": 33,
"ott_percent": 103,
"ott_bw_up": 147,
"tps_qty_index": 106,
"max_risk_long": 64
},
"0331291330650943": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 133,
"tps_qty_index": 65,
"max_risk_long": 94
},
"0560781380350573": {
"ott_len": 56,
"ott_percent": 78,
"ott_bw_up": 138,
"tps_qty_index": 35,
"max_risk_long": 57
},
"0331291710590523": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 171,
"tps_qty_index": 59,
"max_risk_long": 52
},
"0331291471100523": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 147,
"tps_qty_index": 110,
"max_risk_long": 52
},
"0320781161100523": {
"ott_len": 32,
"ott_percent": 78,
"ott_bw_up": 116,
"tps_qty_index": 110,
"max_risk_long": 52
},
"0701701380320523": {
"ott_len": 70,
"ott_percent": 170,
"ott_bw_up": 138,
"tps_qty_index": 32,
"max_risk_long": 52
},
"0331031491100523": {
"ott_len": 33,
"ott_percent": 103,
"ott_bw_up": 149,
"tps_qty_index": 110,
"max_risk_long": 52
},
"0331701710640633": {
"ott_len": 33,
"ott_percent": 170,
"ott_bw_up": 171,
"tps_qty_index": 64,
"max_risk_long": 63
},
"0331501550690523": {
"ott_len": 33,
"ott_percent": 150,
"ott_bw_up": 155,
"tps_qty_index": 69,
"max_risk_long": 52
},
"0331291380840503": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 138,
"tps_qty_index": 84,
"max_risk_long": 50
},
"0701291380570763": {
"ott_len": 70,
"ott_percent": 129,
"ott_bw_up": 138,
"tps_qty_index": 57,
"max_risk_long": 76
},
"0331291490570523": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 149,
"tps_qty_index": 57,
"max_risk_long": 52
},
"0331291491160523": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 149,
"tps_qty_index": 116,
"max_risk_long": 52
},
"68788825492": {
"ott_len": 68,
"ott_percent": 78,
"ott_bw_up": 88,
"tps_qty_index": 25,
"max_risk_long": 49
},
"0330781340640553": {
"ott_len": 33,
"ott_percent": 78,
"ott_bw_up": 134,
"tps_qty_index": 64,
"max_risk_long": 55
},
"0331291710770463": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 171,
"tps_qty_index": 77,
"max_risk_long": 46
},
"0341291490840663": {
"ott_len": 34,
"ott_percent": 129,
"ott_bw_up": 149,
"tps_qty_index": 84,
"max_risk_long": 66
},
"0331291490650663": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 149,
"tps_qty_index": 65,
"max_risk_long": 66
},
"0321291710980523": {
"ott_len": 32,
"ott_percent": 129,
"ott_bw_up": 171,
"tps_qty_index": 98,
"max_risk_long": 52
},
"0451291490590523": {
"ott_len": 45,
"ott_percent": 129,
"ott_bw_up": 149,
"tps_qty_index": 59,
"max_risk_long": 52
},
"0331291490840523": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 149,
"tps_qty_index": 84,
"max_risk_long": 52
},
"0331031490590653": {
"ott_len": 33,
"ott_percent": 103,
"ott_bw_up": 149,
"tps_qty_index": 59,
"max_risk_long": 65
},
"0301471471100553": {
"ott_len": 30,
"ott_percent": 147,
"ott_bw_up": 147,
"tps_qty_index": 110,
"max_risk_long": 55
},
"0330941470920553": {
"ott_len": 33,
"ott_percent": 94,
"ott_bw_up": 147,
"tps_qty_index": 92,
"max_risk_long": 55
},
"0311031390420563": {
"ott_len": 31,
"ott_percent": 103,
"ott_bw_up": 139,
"tps_qty_index": 42,
"max_risk_long": 56
},
"0340861470860523": {
"ott_len": 34,
"ott_percent": 86,
"ott_bw_up": 147,
"tps_qty_index": 86,
"max_risk_long": 52
},
"0451291490770553": {
"ott_len": 45,
"ott_percent": 129,
"ott_bw_up": 149,
"tps_qty_index": 77,
"max_risk_long": 55
},
"0331291490590913": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 149,
"tps_qty_index": 59,
"max_risk_long": 91
},
"0331291471040773": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 147,
"tps_qty_index": 104,
"max_risk_long": 77
},
"0331031160930523": {
"ott_len": 33,
"ott_percent": 103,
"ott_bw_up": 116,
"tps_qty_index": 93,
"max_risk_long": 52
},
"0321031491100503": {
"ott_len": 32,
"ott_percent": 103,
"ott_bw_up": 149,
"tps_qty_index": 110,
"max_risk_long": 50
},
"70788869522": {
"ott_len": 70,
"ott_percent": 78,
"ott_bw_up": 88,
"tps_qty_index": 69,
"max_risk_long": 52
},
"0331701560110653": {
"ott_len": 33,
"ott_percent": 170,
"ott_bw_up": 156,
"tps_qty_index": 11,
"max_risk_long": 65
},
"0320781481040913": {
"ott_len": 32,
"ott_percent": 78,
"ott_bw_up": 148,
"tps_qty_index": 104,
"max_risk_long": 91
},
"0330781471100523": {
"ott_len": 33,
"ott_percent": 78,
"ott_bw_up": 147,
"tps_qty_index": 110,
"max_risk_long": 52
},
"0331291491100523": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 149,
"tps_qty_index": 110,
"max_risk_long": 52
},
"0310940951100553": {
"ott_len": 31,
"ott_percent": 94,
"ott_bw_up": 95,
"tps_qty_index": 110,
"max_risk_long": 55
},
"0331291490770523": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 149,
"tps_qty_index": 77,
"max_risk_long": 52
},
"0331031470990523": {
"ott_len": 33,
"ott_percent": 103,
"ott_bw_up": 147,
"tps_qty_index": 99,
"max_risk_long": 52
},
"0331291490750553": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 149,
"tps_qty_index": 75,
"max_risk_long": 55
},
"0310941491060553": {
"ott_len": 31,
"ott_percent": 94,
"ott_bw_up": 149,
"tps_qty_index": 106,
"max_risk_long": 55
},
"0331031250590653": {
"ott_len": 33,
"ott_percent": 103,
"ott_bw_up": 125,
"tps_qty_index": 59,
"max_risk_long": 65
},
"0321031491060523": {
"ott_len": 32,
"ott_percent": 103,
"ott_bw_up": 149,
"tps_qty_index": 106,
"max_risk_long": 52
},
"0321031471100913": {
"ott_len": 32,
"ott_percent": 103,
"ott_bw_up": 147,
"tps_qty_index": 110,
"max_risk_long": 91
},
"0331291390590523": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 139,
"tps_qty_index": 59,
"max_risk_long": 52
},
"0331031490990523": {
"ott_len": 33,
"ott_percent": 103,
"ott_bw_up": 149,
"tps_qty_index": 99,
"max_risk_long": 52
},
"0331701490570523": {
"ott_len": 33,
"ott_percent": 170,
"ott_bw_up": 149,
"tps_qty_index": 57,
"max_risk_long": 52
},
"0331030930990523": {
"ott_len": 33,
"ott_percent": 103,
"ott_bw_up": 93,
"tps_qty_index": 99,
"max_risk_long": 52
},
"0331291490920553": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 149,
"tps_qty_index": 92,
"max_risk_long": 55
},
"0330781490840673": {
"ott_len": 33,
"ott_percent": 78,
"ott_bw_up": 149,
"tps_qty_index": 84,
"max_risk_long": 67
},
"70788893512": {
"ott_len": 70,
"ott_percent": 78,
"ott_bw_up": 88,
"tps_qty_index": 93,
"max_risk_long": 51
},
"0331291490750463": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 149,
"tps_qty_index": 75,
"max_risk_long": 46
},
"0331031471030523": {
"ott_len": 33,
"ott_percent": 103,
"ott_bw_up": 147,
"tps_qty_index": 103,
"max_risk_long": 52
},
"0331701490770653": {
"ott_len": 33,
"ott_percent": 170,
"ott_bw_up": 149,
"tps_qty_index": 77,
"max_risk_long": 65
},
"0331291490320523": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 149,
"tps_qty_index": 32,
"max_risk_long": 52
},
"0331031470860523": {
"ott_len": 33,
"ott_percent": 103,
"ott_bw_up": 147,
"tps_qty_index": 86,
"max_risk_long": 52
},
"0331031470500493": {
"ott_len": 33,
"ott_percent": 103,
"ott_bw_up": 147,
"tps_qty_index": 50,
"max_risk_long": 49
},
"0331481490610653": {
"ott_len": 33,
"ott_percent": 148,
"ott_bw_up": 149,
"tps_qty_index": 61,
"max_risk_long": 65
},
"0331031471040493": {
"ott_len": 33,
"ott_percent": 103,
"ott_bw_up": 147,
"tps_qty_index": 104,
"max_risk_long": 49
},
"0331701440590523": {
"ott_len": 33,
"ott_percent": 170,
"ott_bw_up": 144,
"tps_qty_index": 59,
"max_risk_long": 52
},
"0611291380590583": {
"ott_len": 61,
"ott_percent": 129,
"ott_bw_up": 138,
"tps_qty_index": 59,
"max_risk_long": 58
},
"0701030980120503": {
"ott_len": 70,
"ott_percent": 103,
"ott_bw_up": 98,
"tps_qty_index": 12,
"max_risk_long": 50
},
"0331291490930653": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 149,
"tps_qty_index": 93,
"max_risk_long": 65
},
"0320781481100493": {
"ott_len": 32,
"ott_percent": 78,
"ott_bw_up": 148,
"tps_qty_index": 110,
"max_risk_long": 49
},
"0321701310840573": {
"ott_len": 32,
"ott_percent": 170,
"ott_bw_up": 131,
"tps_qty_index": 84,
"max_risk_long": 57
},
"0331701380590653": {
"ott_len": 33,
"ott_percent": 170,
"ott_bw_up": 138,
"tps_qty_index": 59,
"max_risk_long": 65
},
"0310941380570523": {
"ott_len": 31,
"ott_percent": 94,
"ott_bw_up": 138,
"tps_qty_index": 57,
"max_risk_long": 52
},
"0331701490110553": {
"ott_len": 33,
"ott_percent": 170,
"ott_bw_up": 149,
"tps_qty_index": 11,
"max_risk_long": 55
},
"0331291121060523": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 112,
"tps_qty_index": 106,
"max_risk_long": 52
},
"0331031471100523": {
"ott_len": 33,
"ott_percent": 103,
"ott_bw_up": 147,
"tps_qty_index": 110,
"max_risk_long": 52
},
"0701701380670503": {
"ott_len": 70,
"ott_percent": 170,
"ott_bw_up": 138,
"tps_qty_index": 67,
"max_risk_long": 50
},
"0701701381100913": {
"ott_len": 70,
"ott_percent": 170,
"ott_bw_up": 138,
"tps_qty_index": 110,
"max_risk_long": 91
},
"0331031180590453": {
"ott_len": 33,
"ott_percent": 103,
"ott_bw_up": 118,
"tps_qty_index": 59,
"max_risk_long": 45
},
"0331291470920553": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 147,
"tps_qty_index": 92,
"max_risk_long": 55
},
"0331031490680493": {
"ott_len": 33,
"ott_percent": 103,
"ott_bw_up": 149,
"tps_qty_index": 68,
"max_risk_long": 49
},
"0310941471120553": {
"ott_len": 31,
"ott_percent": 94,
"ott_bw_up": 147,
"tps_qty_index": 112,
"max_risk_long": 55
},
"0331291490770663": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 149,
"tps_qty_index": 77,
"max_risk_long": 66
},
"0361701470570523": {
"ott_len": 36,
"ott_percent": 170,
"ott_bw_up": 147,
"tps_qty_index": 57,
"max_risk_long": 52
},
"0310781291100523": {
"ott_len": 31,
"ott_percent": 78,
"ott_bw_up": 129,
"tps_qty_index": 110,
"max_risk_long": 52
},
"0310941471100523": {
"ott_len": 31,
"ott_percent": 94,
"ott_bw_up": 147,
"tps_qty_index": 110,
"max_risk_long": 52
},
"0331031470510523": {
"ott_len": 33,
"ott_percent": 103,
"ott_bw_up": 147,
"tps_qty_index": 51,
"max_risk_long": 52
},
"0701701490770553": {
"ott_len": 70,
"ott_percent": 170,
"ott_bw_up": 149,
"tps_qty_index": 77,
"max_risk_long": 55
},
"0331031471100553": {
"ott_len": 33,
"ott_percent": 103,
"ott_bw_up": 147,
"tps_qty_index": 110,
"max_risk_long": 55
},
"0331291180570523": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 118,
"tps_qty_index": 57,
"max_risk_long": 52
},
"0311031490750553": {
"ott_len": 31,
"ott_percent": 103,
"ott_bw_up": 149,
"tps_qty_index": 75,
"max_risk_long": 55
},
"0321031471100553": {
"ott_len": 32,
"ott_percent": 103,
"ott_bw_up": 147,
"tps_qty_index": 110,
"max_risk_long": 55
},
"0331291110130453": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 111,
"tps_qty_index": 13,
"max_risk_long": 45
},
"0331291481100553": {
"ott_len": 33,
"ott_percent": 129,
"ott_bw_up": 148,
"tps_qty_index": 110,
"max_risk_long": 55
},
"0321291490930913": {
"ott_len": 32,
"ott_percent": 129,
"ott_bw_up": 149,
"tps_qty_index": 93,
"max_risk_long": 91
}
} |
#!/usr/bin/env python
# source venv/bin/activate --> To be in Python Virtual Env
class PlotGraph(GraphScene):
CONFIG = {
"y_max" : 50,
"y_min" : 20,
"x_max" : 7,
"x_min" : 4,
"y_tick_frequency" : 5,
"x_tick_frequency" : 0.5,
"axes_color" : BLUE,
"y_labeled_nums": range(30,60,10),
"x_labeled_nums": list(np.arange(4, 7.0+0.5, 0.5)),
"x_label_decimal":1,
"graph_origin": 3 * DOWN + 6 * LEFT,
"x_label_direction":DOWN,
"y_label_direction":RIGHT,
"x_axis_label": None,
"x_axis_width":10
}
def construct(self):
self.setup_axes(animate=False) #animate=True to add animation
self.x_axis.shift(LEFT*abs(self.y_axis[0].points[0]-self.x_axis[0].points[0]))
self.y_axis.shift(DOWN*abs(self.y_axis[0].points[0]-self.x_axis[0].points[0]))
self.y_axis_label_mob.next_to(self.y_axis[0].get_end(),UP)
p=Dot().move_to(self.coords_to_point(self.x_min, self.y_min))
self.add(p)
graph = self.get_graph(lambda x : x**2,
color = GREEN,
x_min = 5,
x_max = 7
)
self.play(
ShowCreation(graph),
run_time = 2
)
self.wait()
def Range(in_val,end_val,step=1):
return list(np.arange(in_val,end_val+step,step))
class Plot1(GraphScene):
CONFIG = {
"y_max" : 50,
"y_min" : 0,
"x_max" : 7,
"x_min" : 0,
"y_tick_frequency" : 5,
"x_tick_frequency" : 0.5,
"axes_color" : BLUE,
"y_labeled_nums": range(0,60,10),
"x_labeled_nums": list(np.arange(2, 7.0+0.5, 0.5)),
"x_label_decimal":1,
"y_label_direction": RIGHT,
"x_label_direction": UP,
"y_label_decimal":3
}
def construct(self):
self.setup_axes(animate=True)
graph = self.get_graph(lambda x : x**2,
color = GREEN,
x_min = 2,
x_max = 4
)
self.play(
ShowCreation(graph),
run_time = 2
)
self.wait()
class Plot1v2(GraphScene):
CONFIG = {
"y_max" : 50,
"y_min" : 0,
"x_max" : 7,
"x_min" : 0,
"y_tick_frequency" : 5,
"x_tick_frequency" : 1,
"axes_color" : BLUE,
"graph_origin" : np.array((0,0,0))
}
def construct(self):
self.setup_axes(animate=True)
graph = self.get_graph(lambda x : x**2,
color = GREEN,
x_min = 2,
x_max = 4
)
self.play(
ShowCreation(graph),
run_time = 2
)
self.wait()
class Plot2(GraphScene):
CONFIG = {
"y_max" : 50,
"y_min" : 0,
"x_max" : 7,
"x_min" : 0,
"y_tick_frequency" : 5,
"axes_color" : BLUE,
"x_axis_label" : "$t$",
"y_axis_label" : "$f(t)$",
}
def construct(self):
self.setup_axes()
graph = self.get_graph(lambda x : x**2, color = GREEN)
self.play(
ShowCreation(graph),
run_time = 2
)
self.wait()
def setup_axes(self):
# Add this line
GraphScene.setup_axes(self)
# Parametters of labels
# For x
init_label_x = 2
end_label_x = 7
step_x = 1
# For y
init_label_y = 20
end_label_y = 50
step_y = 5
# Position of labels
# For x
self.x_axis.label_direction = DOWN #DOWN is default
# For y
self.y_axis.label_direction = LEFT
# Add labels to graph
# For x
self.x_axis.add_numbers(*range(
init_label_x,
end_label_x+step_x,
step_x
))
# For y
self.y_axis.add_numbers(*range(
init_label_y,
end_label_y+step_y,
step_y
))
# Add Animation
self.play(
ShowCreation(self.x_axis),
ShowCreation(self.y_axis)
)
class Plot3(GraphScene):
CONFIG = {
"y_max" : 50,
"y_min" : 0,
"x_max" : 7,
"x_min" : 0,
"y_tick_frequency" : 10,
"axes_color" : BLUE,
}
def construct(self):
self.setup_axes()
graph = self.get_graph(lambda x : x**2, color = GREEN)
self.play(
ShowCreation(graph),
run_time = 2
)
self.wait()
def setup_axes(self):
GraphScene.setup_axes(self)
# Custom parametters
self.x_axis.add_numbers(*[0,2,5,4])
# Y parametters
init_label_y = 0
end_label_y = 50
step_y = 5
self.y_axis.label_direction = LEFT
self.y_axis.add_numbers(*range(
init_label_y,
end_label_y+step_y,
step_y
))
self.play(Write(self.x_axis),Write(self.y_axis))
class Plot4(GraphScene):
CONFIG = {
"y_max" : 50,
"y_min" : 0,
"x_max" : 7,
"x_min" : 0,
"y_tick_frequency" : 10,
"axes_color" : BLUE,
}
def construct(self):
self.setup_axes()
graph = self.get_graph(lambda x : x**2, color = GREEN)
self.play(
ShowCreation(graph),
run_time = 2
)
self.wait()
def setup_axes(self):
GraphScene.setup_axes(self)
self.x_axis.label_direction = UP
self.x_axis.add_numbers(*[3.5,5,4]) # 3.5 is rounded to 4
self.y_axis.label_direction = LEFT
self.y_axis.add_numbers(*range(0, 50+5, 5))
self.play(Write(self.x_axis),Write(self.y_axis))
class Plot5(GraphScene):
CONFIG = {
"y_max" : 50,
"y_min" : 0,
"x_max" : 7,
"x_min" : 0,
"y_tick_frequency" : 10,
"x_tick_frequency" : 0.5,
"axes_color" : BLUE,
}
def construct(self):
self.setup_axes()
graph = self.get_graph(lambda x : x**2, color = GREEN)
self.play(
ShowCreation(graph),
run_time = 2
)
self.wait()
def setup_axes(self):
GraphScene.setup_axes(self)
self.x_axis.label_direction = UP
values_x = [
(3.5,"3.5"), # (position 3.5, label "3.5")
(4.5,"\\frac{9}{2}") # (position 4.5, label "9/2")
]
self.x_axis_labels = VGroup() # Create a group named x_axis_labels
# pos. tex.
for x_val, x_tex in values_x:
tex = TexMobject(x_tex) # Convert string to tex
tex.scale(0.7)
tex.next_to(self.coords_to_point(x_val, 0), DOWN) #Put tex on the position
self.x_axis_labels.add(tex) #Add tex in graph
self.play(
Write(self.x_axis_labels),
Write(self.x_axis),
Write(self.y_axis)
)
class Plot6(GraphScene):
CONFIG = {
"y_max" : 50,
"y_min" : 0,
"x_max" : 7,
"x_min" : 0,
"y_tick_frequency" : 10,
"x_tick_frequency" : 0.5,
"axes_color" : BLUE,
}
def construct(self):
self.setup_axes()
graph = self.get_graph(lambda x : x**2, color = GREEN)
self.play(
ShowCreation(graph),
run_time = 2
)
self.wait()
def setup_axes(self):
GraphScene.setup_axes(self)
self.x_axis.label_direction = UP
# List of values of positions
values_decimal_x=[0,0.5,1,1.5,3.35]
# Transform positions to tex labels
list_x = [*["%s"%i for i in values_decimal_x]]
# List touples of (position,label)
values_x = [
(i,j)
for i,j in zip(values_decimal_x,list_x)
]
self.x_axis_labels = VGroup()
for x_val, x_tex in values_x:
tex = TexMobject(x_tex)
tex.scale(0.7)
tex.next_to(self.coords_to_point(x_val, 0), DOWN)
self.x_axis_labels.add(tex)
self.play(
Write(self.x_axis_labels),
Write(self.x_axis),
Write(self.y_axis)
)
class Plot7(GraphScene):
CONFIG = {
"y_max" : 50,
"y_min" : 0,
"x_max" : 7,
"x_min" : 0,
"y_tick_frequency" : 10,
"x_tick_frequency" : 0.5,
"axes_color" : BLUE,
}
def construct(self):
self.setup_axes()
graph = self.get_graph(lambda x : x**2, color = GREEN)
self.play(
ShowCreation(graph),
run_time = 2
)
self.wait()
def setup_axes(self):
GraphScene.setup_axes(self)
self.x_axis.label_direction = UP
# Additional parametters
init_val_x = 0
step_x = 0.5
end_val_x = 7
# Position of labels
values_decimal_x=Range(init_val_x,end_val_x,step_x)
# List of labels
list_x=[*["%.1f"%i for i in values_decimal_x]]
# List touples of (posición,etiqueta)
values_x = [
(i,j)
for i,j in zip(values_decimal_x,list_x)
]
self.x_axis_labels = VGroup()
for x_val, x_tex in values_x:
tex = TexMobject(x_tex)
tex.scale(0.7)
tex.next_to(self.coords_to_point(x_val, 0), DOWN)
self.x_axis_labels.add(tex)
self.play(
Write(self.x_axis_labels),
Write(self.x_axis),
Write(self.y_axis)
)
class PlotSinCos(GraphScene):
CONFIG = {
"y_max" : 1.5,
"y_min" : -1.5,
"x_max" : 3*PI/2,
"x_min" : -3*PI/2,
"y_tick_frequency" : 0.5,
"x_tick_frequency" : PI/2,
"graph_origin" : ORIGIN,
"y_axis_label": None, # Don't write y axis label
"x_axis_label": None,
}
def construct(self):
self.setup_axes()
plotSin = self.get_graph(lambda x : np.sin(x),
color = GREEN,
x_min=-4,
x_max=4,
)
plotCos = self.get_graph(lambda x : np.cos(x),
color = GRAY,
x_min=-PI,
x_max=0,
)
plotSin.set_stroke(width=3) # width of line
plotCos.set_stroke(width=2)
# Animation
for plot in (plotSin,plotCos):
self.play(
ShowCreation(plot),
run_time = 2
)
self.wait()
def setup_axes(self):
GraphScene.setup_axes(self)
# width of edges
self.x_axis.set_stroke(width=2)
self.y_axis.set_stroke(width=2)
# color of edges
self.x_axis.set_color(RED)
self.y_axis.set_color(YELLOW)
# Add x,y labels
func = TexMobject("\\sin\\theta")
var = TexMobject("\\theta")
func.set_color(BLUE)
var.set_color(PURPLE)
func.next_to(self.y_axis,UP)
var.next_to(self.x_axis,RIGHT+UP)
# Y labels
self.y_axis.label_direction = LEFT*1.5
self.y_axis.add_numbers(*[-1,1])
#Parametters of x labels
init_val_x = -3*PI/2
step_x = PI/2
end_val_x = 3*PI/2
# List of the positions of x labels
values_decimal_x=Range(init_val_x,end_val_x,step_x)
# List of tex objects
list_x=TexMobject("-\\frac{3\\pi}{2}", # -3pi/2
"-\\pi", # -pi
"-\\frac{\\pi}{2}", # -pi/2
"\\,", # 0 (space)
"\\frac{\\pi}{2}", # pi/2
"\\pi",# pi
"\\frac{3\\pi}{2}" # 3pi/2
)
#List touples (position,label)
values_x = [(i,j)
for i,j in zip(values_decimal_x,list_x)
]
self.x_axis_labels = VGroup()
for x_val, x_tex in values_x:
x_tex.scale(0.7)
if x_val == -PI or x_val == PI: #if x is equals -pi or pi
x_tex.next_to(self.coords_to_point(x_val, 0), 2*DOWN) #Put 2*Down
else: # In another case
x_tex.next_to(self.coords_to_point(x_val, 0), DOWN)
self.x_axis_labels.add(x_tex)
self.play(
*[Write(objeto)
for objeto in [
self.y_axis,
self.x_axis,
self.x_axis_labels,
func,var
]
],
run_time=2
) |
"""
A variety of examples to showcase useage of pix.
Note that some libraries or other thirdparty resources may be required to run
an example.
""" |
class linkedListNode(object): # ListNode继承object中的方法
def __init__(self, initData):
self.data = initData
self.next = None
def _getData(self):
return self.data
def _getNext(self):
return self.next
def _setData(self, newData):
self.data = newData
def _setNext(self, newNext):
self.next = newNext
class linkedListOperation():
def __init__(self):
self.currentNode = None
def clear(self):
return self.currentNode._setNext(None)
def insert(self, data):
temp = linkedListNode(data)
temp._setNext(self.currentNode)
self.currentNode = temp
return temp
def size(self):
current = self.currentNode
cnt = 0
while current != None:
cnt += 1
current = current._getNext()
return cnt
def search(self, data):
current = self.currentNode
found = False
while current != None and not found:
if current._getData() == data:
return current
else:
current = current._getNext()
return found
# current = self.currentNode
# found = False
# while current != None and not found:
# if current._getData() == item:
# found = True
# else:
# current = current._getNext()
# return found
def remove(self, data):
previous = None
current = self.currentNode
while current != None:
if current._getData() == data and previous == None:
previous = current._getNext()
return previous
elif current._getData() == data and previous != None:
previous._setNext(current._getNext())
return previous
else:
previous = current
current = current._getNext()
return 'no node like this!'
# previous = None
# current = self.currentNode
#
# while current != None:
# if current._getData() == data and previous != None:
# previous._setNext(current._getNext())
# return previous
# else:
# previous = current
# current = current._getNext()
#
# if previous == None:
# previous = current._getNext()
# return previous
# else:
# previous._setNext(current._getNext())
# return 'no node like this!'
def findKthToTail(self, pHead, k):
self.currentNode = pHead
size = self.size()
cnt = 0
temp = pHead
while size - cnt != k and temp != None:
temp = temp._getNext()
cnt += 1
if temp == None:
return None
return temp._getData()
def reverse(self, pHead):
self.currentNode = pHead
if pHead != None:
previous = pHead
current = previous._getNext()
while current != None:
temp = current._getNext()
current._setNext(pHead)
previous._setNext(temp)
pHead = current
current = temp
return pHead
def deleteDuplication(self, pHead):
# write code here
# previous = pHead
current = pHead
splitNode_lst = []
splitVal_lst = []
while current is not None:
splitNode_lst.append(current)
splitVal_lst.append(current._getData())
current = current._getNext()
splitVal_lst_n = []
for i in range(len(splitVal_lst)):
if splitVal_lst.count(splitVal_lst[i]) == 1:
splitVal_lst_n.append(splitVal_lst[i])
if len(splitVal_lst_n) == 0:
return
temp = linkedListNode(splitVal_lst_n[0])
pre = temp
for i in range(1, len(splitVal_lst_n)):
if splitVal_lst_n[i - 1] != splitVal_lst_n[i]:
new = linkedListNode(splitVal_lst_n[i])
pre._setNext(new)
pre = pre._getNext()
return temp
def insertOrderd(self, pHead, data):
previous = None
current = pHead
inserted = False
temp = linkedListNode(data)
if current._getData() > data and previous == None:
temp._setNext(pHead)
# pHead = temp # TODO: 实际效果为 temp = pHead ?????
return temp
previous = current
current = current._getNext()
while previous is not None and current is not None and not inserted:
if not current._getData() < data:
# temp = current
previous._setNext(temp)
temp._setNext(current)
inserted = True
previous = current
current = current._getNext()
if not previous._getData() > data:
previous._setNext(temp)
return pHead
def mergeTwoOrderedList_v2(self, pHead1, pHead2):
# TODO: cost too many times
current = pHead2
while current is not None:
currentData = current._getData()
current = current._getNext()
pHead1 = self.insertOrderd(pHead1, currentData)
return pHead1
def mergeTwoOrderedList_v3(self, pHead1, pHead2):
# TODO:
current = pHead1
current2 = pHead2
previous = None
inserted = False
currentData = data
temp = linkedListNode(data)
if current2._getData() > data and previous == None:
# insert pHead2.current2 before head node of pHead1
temp._setNext(pHead1)
pHead1 = temp # TODO: 实际效果为 temp = pHead ?????
# return temp
previous = current
current = current._getNext()
while current2 is not None and previous is not None and current is not None and not inserted:
currentData = current2._getData()
current2 = current2._getNext()
if not current._getData() < currentData:
# temp = current
previous._setNext(temp)
temp._setNext(current)
inserted = True
previous = current
current = current._getNext()
# pHead1 = self.insertOrderd(pHead1, currentData)
if not previous._getData() > currentData:
previous._setNext(temp)
return pHead1
def mergeTwoOrderedList(self, pHead1, pHead2):
# write code here
temp1_previous = None
temp1_previous2 = None
temp1 = pHead1
temp2 = pHead2
while temp1 != None and temp2 != None:
if temp1._getData() < temp2._getData():
# insert temp2.val behind temp1.val in temp1
temp_temp1 = temp1._getNext()
temp1._setNext(temp2)
temp_temp2 = temp2._getNext()
temp2._setNext(temp_temp1)
temp1_previous = temp1
temp1 = temp_temp1
temp2 = temp_temp2
else:
# insert temp2.val before temp.val in temp1
if temp1_previous is not None:
temp1_previous = temp1_previous._getNext()
# temp_temp1 = temp1._getNext()
temp_temp2 = temp2._getNext()
temp2._setNext(temp1)
temp1_previous._setNext(temp2) # 执行完后pHead会随之改变
# temp2._setNext(temp_temp1)
# temp1_previous = temp1
# temp1 = temp_temp1
temp2 = temp_temp2
else:
# TODO
# temp_temp1 = temp1._getNext()
# temp_temp2 = temp2._getNext()
temp2._setNext(pHead1)
pHead1 = temp2
# temp1 = temp_temp1
# temp2 = temp_temp2
temp1_previous = temp2
# if temp1 == None:
# temp1_previous._setNext(temp2)
return pHead1
def FindFirstCommonNode(self, pHead1, pHead2):
"""
输入两个链表,找出它们的第一个公共结点。
TODO: input: {1,2,3},{4,5},{6,7} <{1,2,3,6,7} and {4,5,6,7}>; expect: {6,7}; actual: {} ?????
TODO: reason: must reach the common node at same time
:param pHead1:
:param pHead2:
:return:
"""
# write code here
current2 = pHead2
current1 = pHead1
if current1 is None or current2 is None:
return
ph1Val_lst = []
ph1Nod_lst = []
ph2Val_lst = []
ph2Nod_lst = []
while current1 is not None:
ph1Val_lst.append(current1._getData())
ph1Nod_lst.append(current1)
current1 = current1._getNext()
while current2 is not None:
ph2Val_lst.append(current2._getData())
ph2Nod_lst.append(current2)
current2 = current2._getNext()
for i, x in enumerate(ph1Val_lst):
if x in ph2Val_lst:
return ph1Nod_lst[i]
# else:
# return
# for i, x in enumerate(ph2Val_lst):
# if x in ph1Val_lst:
# return ph2Nod_lst[i]
# else:
# return
# # l1 = linkedListNode(9)
# l1_op = linkedListOperation()
# for data in [1, 8, 4, 11, 7]:
# l1 = l1_op.insert(data)
# # print(l1_op.add(data)._getData(), l1_op.add(data)._getNext())
# print('\n', l1, l1.data, l1.next, '\n', l1.next.data, l1.next.next, '\n', l1_op.size(), l1_op.search(4))
# print(l1_op.size(), l1_op.search(1), l1_op.search(8), l1_op.search(4), l1_op.search(11), l1_op.search(7), l1_op.search(111))
# print(l1_op.size(), l1_op.remove(3), l1_op.remove(1), l1_op.remove(8), l1_op.remove(7))
# print(l1_op.reverse({}), l1_op.reverse(l1))
# print(l1_op.findKthToTail(l1, 4), l1_op.findKthToTail(l1, 12))
# # l1 = linkedListNode(9)
# l111_op = linkedListOperation()
# for data in [200, 4, 1]:
# l11 = l111_op.insert(data)
# # print(l1_op.add(data)._getData(), l1_op.add(data)._getNext())
# print(l111_op.insertOrderd(l11, 18)._getNext()._getNext()._getData())
#
# l111_op.clear()
# l112_op = linkedListOperation()
# for data in [200, 18, 4]:
# l11 = l112_op.insert(data)
# # print(l1_op.add(data)._getData(), l1_op.add(data)._getNext())
# l112 = l112_op.insertOrderd(l11, 1)
# print(l112_op.insertOrderd(l11, 1)._getData())
#
# l2_op = linkedListOperation()
# for data in [91, 19, 9, 5, 2]:
# l12 = l2_op.insert(data)
# # print(l1_op.add(data)._getData(), l1_op.add(data)._getNext())
# print('\n', l1, l1.data, l1.next, '\n', l1.next.data, l1.next.next, '\n', l1_op.size(), l1_op.search(4))
# print(l1_op.size(), l1_op.search(1), l1_op.search(8), l1_op.search(4), l1_op.search(11), l1_op.search(7), l1_op.search(111))
# print(l1_op.size(), l1_op.remove(3), l1_op.remove(1), l1_op.remove(8), l1_op.remove(7))
# print(l1_op.reverse({}), l1_op.reverse(l1))
# print(l1_op.mergeTwoOrderedList(l11, l12))
# l112_op = linkedListOperation()
# for data in [5, 3, 1]:
# l11 = l112_op.insert(data)
# # print(l1_op.add(data)._getData(), l1_op.add(data)._getNext())
# # print(l112_op.insertOrderd(l11, 1)._getData())
#
# l2_op = linkedListOperation()
# for data in [6, 4, 2]:
# l12 = l2_op.insert(data)
# print(l1_op.add(data)._getData(), l1_op.add(data)._getNext())
# print(l2_op.mergeTwoOrderedList_v2(l11, l12))
# print(l2_op.mergeTwoOrderedList_v3(l11, l12))
# l112_op = linkedListOperation()
# for data in [7, 6, 3, 2, 1]:
# l11 = l112_op.insert(data)
# # print(l1_op.add(data)._getData(), l1_op.add(data)._getNext())
# # print(l112_op.insertOrderd(l11, 1)._getData())
#
# l2_op = linkedListOperation()
# for data in [7, 6, 5, 4]:
# l12 = l2_op.insert(data)
# print(l2_op.FindFirstCommonNode(l11, l12))
l112_op = linkedListOperation()
# for data in [7, 6, 4, 4, 3, 3, 2, 1]:
for data in [2, 1, 1, 1, 1]:
l11 = l112_op.insert(data)
# print(l1_op.add(data)._getData(), l1_op.add(data)._getNext())
# print(l112_op.insertOrderd(l11, 1)._getData())
print(l112_op.deleteDuplication(l11))
|
class Configuration(object):
def __init__(self, **kwargs):
for key, value in kwargs.items():
if isinstance(value, dict):
value = Configuration(**value)
setattr(self, key, value)
def to_dict(self):
rv = {}
for key, value in self.__dict__.items():
if isinstance(value, Configuration):
value = value.to_dict()
rv[key] = value
return rv
def __str__(self):
return str(self.to_dict())
def __repr__(self):
return f"<{self.__class__.__name__} '{str(self)}'>"
|
product = input()
day = input()
quantity = float(input())
price = 0
isError = False
if day == 'Saturday' or day == 'Sunday':
if product == 'banana':
price = 2.7
elif product == 'apple':
price = 1.25
elif product == 'orange':
price = 0.9
elif product == 'grapefruit':
price = 1.60
elif product == 'kiwi':
price = 3
elif product == 'pineapple':
price = 5.6
elif product == 'grapes':
price = 4.2
else:
print('error')
isError = True
elif day == 'Monday' or day == 'Tuesday' or day == 'Wednesday' or day == 'Thursday' or day == 'Friday':
if product == 'banana':
price = 2.5
elif product == 'apple':
price = 1.2
elif product == 'orange':
price = 0.85
elif product == 'grapefruit':
price = 1.45
elif product == 'kiwi':
price = 2.7
elif product == 'pineapple':
price = 5.5
elif product == 'grapes':
price = 3.85
else:
print('error')
isError = True
else:
print('error')
isError = True
if isError == False:
print(f"{(price * quantity):.2f}") |
# -*- coding: utf-8 -*-
class Precipitation(object):
def __init__(self, precipitation):
self.value = float(precipitation['value'])
try:
self.minValue = float(precipitation['minvalue'])
except KeyError:
self.minValue = None
try:
self.maxValue = float(precipitation['maxvalue'])
except KeyError:
self.maxValue = None
def __str__(self):
return '\t\t\t\tValue: {0} \n\t\t\t\tMinValue: {1} \n\t\t\t\tMaxValue: {2}'.format(self.value, self.minValue, self.maxValue) |
def run():
r.setpos(0,0,0)
|
class Command:
TO_CN = 1
TO_EN = 2
JSON_FORMAT = 3
URL_ENCODE = 4
URL_DECODE = 5 |
# Выполнить логические побитовые операции «И», «ИЛИ» и др. над числами 5 и 6.
# Выполнить над числом 5 побитовый сдвиг вправо и влево на два знака.
# Объяснить полученный результат.
print("5 & 6 = %d" % (5 & 6)) # Бинарное И 101 & 110 = 100
print("5 | 6 = %d" % (5 | 6)) # Бинарное ИЛИ 101 & 110 = 111
print("5 ^ 6 = %d" % (5 ^ 6)) # Бинарное исключающее ИЛИ 101 & 110 = 11
print("5 << 2 = %d" % (5 << 2)) # Побитовый сдвиг влево 5 (101) << 2 = 20 (10100)
print("5 >> 2 = %d" % (5 >> 2)) # Побитовый сдвиг вправо 5 (101) >> 2 = 1 (1)
|
# checking for armstrong number
a = input("Enter a number")
n = int(a)
S = 0
while n > 0:
d = n % 10
S = S + d * d * d
n = n / 10
if int(a) == S:
print("Armstrong Number")
else:
print("Not an Armstrong Number")
|
class BuildEnvironmentError(Exception):
def __init__(self, msg, build_env):
self.msg = msg
self.build_env = build_env
def __str__(self):
return "{}({})".format(self.__class__.__name__, repr(self.msg))
class VariantDBConnectionError(BuildEnvironmentError):
def __init__(self, connection, build_env):
self.connection = connection
self.msg = "Could not connect to database \"{}\"".format(connection)
self.build_env = build_env
|
"""
假设有打乱顺序的一群人站成一个队列。 每个人由一个整数对(h, k)表示,其中h是这个人的身高,k是排在这个人前面且身高大于或等于h的人数。 编写一个算法来重建这个队列。
注意:
总人数少于1100人。
示例
输入:
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
输出:
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]
"""
class Solution:
def reconstructQueue(self, people):
people.sort(key=lambda x: (x[0], -x[1])) # lambada 是一个隐函数,x表示列表中的一个元素,x只是临时起的一个名字,你可以使用任意的名字
# x[0]表示列表里的第一个元素,默认是升序排列,reverse可以默认值为False。这句话的意思是一纬按照升序排列,二维按照降序。
# 经过排序之后,我们会发现:身高高的人插在身高矮的人面前,必定会对矮的人的k造成影响。然而,身高矮的人插在身高高的人面前必定不会产生影响。
# 因此 我们可以先做一个跟人数一样多的空的数列。第 i个人的位置,就是队列中从左往右数第k+1个「空」位置。
# print(people)
n = len(people)
ans = [[] for _ in range(n)] # 创建空数列
for person in people:
spaces = person[1] + 1
for i in range(n):
if not ans[i]: # 如果不是False 等同于ans[i]为0的时候是True,space-1
spaces -= 1
if spaces == 0: # 如果space为0了 那就是找到了,这个空位就是person
ans[i] = person
break
return ans
people = [[7, 0], [4, 4], [7, 1], [5, 0], [6, 1], [5, 2]]
Solution().reconstructQueue(people)
# 作者:LeetCode-Solution
# 链接:https://leetcode-cn.com/problems/queue-reconstruction-by-height/solution/gen-ju-shen-gao-zhong-jian-dui-lie-by-leetcode-sol/
# 来源:力扣(LeetCode)
# 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
|
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param l1: the first list
@param l2: the second list
@return: the sum list of l1 and l2
"""
def addLists(self, l1, l2):
dummy = tail = ListNode(0)
carry = 0
while l1 is not None or l2 is not None or carry == 1:
tail.next = ListNode(carry)
tail = tail.next
if l1 is not None:
tail.val += l1.val
l1 = l1.next
if l2 is not None:
tail.val += l2.val
l2 = l2.next
if tail.val > 9:
tail.val -= 10
carry = 1
else:
carry = 0
return dummy.next |
#Advanced string syntax
#Multiple ways to type strings
print('Hello')
print("That is Alice's cat")
#To use a single quote throughout your code
#put in a / before the quotation
print('Here is the example (\')')
print('Do you see how the quotation \' is shown?')
#Example of types of "Escape Characters"
# \' = Single Quote
# \" = Double Quote
# \t = Tab
# \n = New Line (Line break)
# \\ = Backslash
print('Hello there! \nHow are you? \n I\'m fine.')
# Multi line strings start with """. The """ enables the user to code without using the escape characters
print("""This is an example of use of the multi string.
Dear Alice,
Eve's cat has been arrested for catnapping, cat burglary, and extortion.
Sincerely,
Drew.""")
#Now we will attache this to a variable spam
spam = print("""This is an example of use of the multi string.
Dear Alice,
Eve's cat has been arrested for catnapping, cat burglary, and extortion.
Sincerely,
Drew.""")
spam
|
class Queue:
def __init__(self):
self.queue = list()
def enqueue(self,data):
if data not in self.queue:
self.queue.insert(0,data)
return True
return False
def dequeue(self):
if len(self.queue)>0:
return self.queue.pop()
return ("Queue Empty!")
def size(self):
return len(self.queue)
def printQueue(self):
return self.queue
myQueue = Queue()
print(myQueue.enqueue(5))
print(myQueue.enqueue(6))
print(myQueue.enqueue(9))
print(myQueue.enqueue(5))
print(myQueue.enqueue(3))
print(myQueue.size())
print(myQueue.dequeue())
print(myQueue.dequeue())
print(myQueue.dequeue())
print(myQueue.dequeue())
print(myQueue.size())
print(myQueue.dequeue())
|
class Solution(object):
def findDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums) - 1
start, end = 1, n
while start + 1 < end:
mid = start + (end - start) / 2
count = 0
for num in nums:
if num < mid:
count += 1
if count >= mid:
end = mid
else:
start = mid
if nums.count(start) > nums.count(end):
return start
return end
|
class TerminalSet:
NODE_TYPE = 'terminal'
@classmethod
def is_terminal_value(cls, node):
return node['node_type'] == cls.NODE_TYPE and node.has_key('value') and (node['type'] in ['int', 'float'])
@classmethod
def terminal_value(cls, value):
return {'node_type': cls.NODE_TYPE, 'name': str(value), 'value': value, 'type': type(value).__name__}
def __init__(self):
self.terminal_set = []
def add_terminal_value(self, name, value):
self.terminal_set.append({'node_type': self.NODE_TYPE, 'name': name, 'value': value, 'type': type(value).__name__})
def add_terminal_function(self, name, func_ref, value_type, args=[]):
self.terminal_set.append({'node_type': self.NODE_TYPE, 'name': name, 'function': func_ref, 'type': value_type, 'args': args})
def add_terminal_function_to_value(self, func_ref, args=[]):
self.terminal_set.append({'node_type': self.NODE_TYPE, 'function': func_ref, 'args': args})
def get(self):
return self.terminal_set
|
"""
Parameters exchanged client <-> server and client <-> compensator
Copyright 2021 Reza NasiriGerdeh and Reihaneh TorkzadehMahani. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
class Parameter:
"""
There are nine general categories of the parameters exchanged clients <-> server and client <-> compensator:
client -> server: authentication, synchronization, monitoring, and local parameters
server -> client: coordination, project, and global parameters
client -> compensator: authentication, synchronization, connection, data_type, and compensation parameters
compensator -> client: synchronization parameters
"""
AUTHENTICATION = "authentication_parameter"
SYNCHRONIZATION = "synchronization_parameter"
MONITORING = "monitoring_parameter"
PROJECT = "project_parameter"
COORDINATION = "coordination_parameter"
CONNECTION = "connection_parameter"
GLOBAL = "global_parameter"
LOCAL = "local_parameter"
COMPENSATION = "compensation_parameter"
DATA_TYPE = "data_type_parameter"
class AuthenticationParameter:
""" Parameters to authenticate the client """
# client -> server
USERNAME = "username"
PASSWORD = "password"
PROJECT_ID = "project_id"
TOKEN = "token"
# client -> compensator
HASH_USERNAME = "hash_username"
HASH_TOKEN = "hash_token"
HASH_PROJECT_ID = "hash_project_id"
class SyncParameter:
""" Client -> server or client <-> compensator parameters to ensure clients, server, and compensator are synced """
# client -> server and client -> compensator
PROJECT_STEP = "project_step"
COMM_ROUND = "communication_round"
# client -> server
OPERATION_STATUS = "operation_status"
COMPENSATOR_FLAG = "compensator_flag"
# compensator -> client
SHOULD_RETRY = "should_retry"
class MonitoringParameter:
""" Client -> server parameters to breakdown the runtime of the client """
COMPUTATION_TIME = "computation_time"
NETWORK_SEND_TIME = "network_send_time"
NETWORK_RECEIVE_TIME = "network_receive_time"
IDLE_TIME = "idle_time"
class HyFedProjectParameter:
""" Server -> client project parameters """
ID = "id"
TOOL = "tool"
ALGORITHM = "algorithm"
NAME = "name"
DESCRIPTION = "description"
COORDINATOR = "coordinator"
class CoordinationParameter:
""" Server -> client parameters for coordination purposes """
PROJECT_ID = "project_id"
PROJECT_STATUS = "project_status"
PROJECT_STEP = "project_step"
COMM_ROUND = "communication_round"
PROJECT_STARTED = "project_started"
CLIENT_JOINED = "client_joined"
class ConnectionParameter:
""" Mostly used in the client """
SERVER_NAME = "server_name"
SERVER_URL = "server_url" # client -> compensator
COMPENSATOR_NAME = "compensator_name"
COMPENSATOR_URL = "compensator_url"
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2019 Idiap Research Institute, http://www.idiap.ch/
# Written by Bastian Schnell <[email protected]>
#
class EmbeddingConfig(object):
def __init__(self, f_get_emb_index, num_embeddings, embedding_dim, name=None, **args):
assert callable(f_get_emb_index), "f_get_emb_index must be callable."
self.f_get_emb_index = f_get_emb_index
self.num_embeddings = num_embeddings
self.embedding_dim = embedding_dim
self.name = name
self.args = args
def __repr__(self):
if self.name is None:
output = ""
else:
output = "{}: ".format(self.name)
output += "{}x{}".format(self.num_embeddings, self.embedding_dim)
if len(self.args.keys()) > 0:
output += "with " + " ".join(map(str, **self.args))
return output
|
y=int(input("Enter The year: "))
if(((y%2==0)or (y%400==0))and y%100!=0):
print("leap Year")
else:
print("Not Leap year")
|
class Notifier:
def __init(self):
pass
def notify(self, msg):
print(msg)
def message(self, msg):
print(msg)
def message2(self, msg2):
print(msg2) |
# -*- coding: utf-8 -*-
"""Version information for the bioregistry."""
__all__ = [
'VERSION',
]
VERSION = '0.1.4-dev'
|
class Solution:
def reverseWords(self, s: str) -> str:
list1 = s.split(' ')[::-1]
new_string = ""
for i in range(0,len(list1)):
if(list1[i]!=""):
if(len(new_string)>0):
new_string+=" "
new_string+=list1[i]
return new_string
|
# fig03_03.py
"""Using nested control statements to analyze examination results."""
# initialize variables
passes = 0 # number of passes
failures = 0 # number of failures
# process 10 students
for student in range(10):
# get one exam result
result = int(input('Enter result (1=pass, 2=fail): '))
if result == 1:
passes = passes + 1
else:
failures = failures + 1
# termination phase
print('Passed:', passes)
print('Failed:', failures)
if passes > 8:
print('Bonus to instructor')
##########################################################################
# (C) Copyright 2019 by Deitel & Associates, Inc. and #
# Pearson Education, Inc. All Rights Reserved. #
# #
# DISCLAIMER: The authors and publisher of this book have used their #
# best efforts in preparing the book. These efforts include the #
# development, research, and testing of the theories and programs #
# to determine their effectiveness. The authors and publisher make #
# no warranty of any kind, expressed or implied, with regard to these #
# programs or to the documentation contained in these books. The authors #
# and publisher shall not be liable in any event for incidental or #
# consequential damages in connection with, or arising out of, the #
# furnishing, performance, or use of these programs. #
##########################################################################
|
"""
Write a program which accepts an integer value as command line and print “Ok” if value is between 1 to 50 (both inclusive) otherwise it prints ”Out of range”.
"""
number = int(input("Enter a number: "))
if number > 0 and number < 51:
print("Ok")
else:
print("Out of range") |
def relay_states_registar_value(relay_states):
num = 0
n = 8
for relay_state in relay_states:
if relay_state:
num += 2**n
n += 1
return num
def relay_states_from_register_value(value):
relay_states = []
num = value
for i in range(11, 7, -1):
if num >= 2**i:
num -= 2**i
relay_states.append(1)
else:
relay_states.append(0)
return relay_states
|
"""User variables to use toolkit for Dynatrace"""
FULL_SET = {
"CLUSTER_NAME": {
"url":"URL GOES HERE (EVEN FOR SAAS)",
"tenant": {
"tenant1": "TENANT UUID GOES HERE",
"tenant2": "TENANT UUID GOES HERE"
},
"api_token": {
"tenant1": "API TOKEN GOES HERE",
"tenant2": "API TOKEN GOES HERE",
},
"is_managed": True,
"cluster_token": "Required for Cluster Operations in Managed"
}
}
# ROLE TYPE KEYS
# access_env
# change_settings
# install_agent
# view_logs
# view_senstive
# change_sensitive
USER_GROUPS = {
"role_types":{
"access_env": "accessenv",
"change_settings": "changesettings",
"view_logs": "logviewer",
"view_sensitive": "viewsensitive"
},
"role_tenants":[
"nonprod",
"prod"
]
}
USER_GROUP_TEMPLATE = "prefix_{USER_TYPE}_{TENANT}_{APP_NAME}_suffix"
DEFAULT_TIMEZONE = "America/Chicago"
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (C) 2012 Yahoo! Inc. All Rights Reserved.
# Copyright (C) 2012 New Dream Network, LLC (DreamHost) All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
def partition(fullname):
"""
The name should be in dotted.path:ClassName syntax.
"""
if ':' not in fullname:
raise ValueError('Invalid entry point specifier %r' % fullname)
(module_name, _, classname) = fullname.partition(':')
return (module_name, classname)
def import_entry_point(fullname):
"""
Given a name import the class and return it.
"""
(module_name, classname) = partition(fullname)
try:
module = __import__(module_name)
for submodule in module_name.split('.')[1:]:
module = getattr(module, submodule)
cls = getattr(module, classname)
except (ImportError, AttributeError) as err:
raise RuntimeError('Could not load entry point %s: %s' %
(fullname, err))
return cls
|
# for loop
# Iterating over a list
print("List Iteration")
l = ["Ankit", "Gupta"]
for i in l:
print(i)
# Iterating over a tuple (immutable)
print("\nTuple Iteration")
t = ("ankit", "gupta")
for i in t:
print(i)
# Iterating over a String
print("\nString Iteration")
s = "Ankit"
for i in s:
print(i)
# Iterating over dictionary
print("\nDictionary Iteration")
d = dict()
d['xyz'] = 123
d['abc'] = 345
for i in d:
print("% s % d" % (i, d[i]))
# for loop Using range() function
# Factorial of number
num = int(input('Number:'))
factorial = 1
# check if the number is negative, positive or zero
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
# printing a number
for i in range(10):
print(i, end=" ")
print()
# using range for iteration
l = [10, 20, 30, 40]
for i in range(len(l)):
print(l[i], end=" ")
print()
# performing sum of first 10 numbers
sum = 0
for i in range(1, 10):
sum = sum + i
print("Sum of first 10 numbers :", sum)
# Program to print table of given number
n = int(input("Enter the number "))
for i in range(1,11):
c = n*i
print(n,"*",i,"=",c)
# Program to print even number using step size in range()
n = int(input("Enter the number "))
for i in range(2,n,2):
print(i)
# Python program to demonstrate for-else loop
for i in range(1, 4):
print(i)
else: # Executed because no break in for
print("No Break")
for i in range(1, 4):
print(i)
break
else: # Not executed as there is a break
print("Break")
|
'''
Created on 2015年12月12日
@author: Darren
'''
|
with open('html_file.html','r') as rf:
with open('output.txt','w') as of:
for string in rf.readlines():
if "<a href=" in string :
of.write(string)
#Some Better Solution for video lecture no. 223 |
#!/usr/bin/env python
input = input("Enter IP address: ")
octets = input.split(".")
first_octet = bin(int(octets[0]))
second_octet = bin(int(octets[1]))
third_octet = bin(int(octets[2]))
forth_octet = bin(int(octets[3]))
print("%-20s%-20s%-20s%-20s" % ("First Octet", "Second Octet",
"Third Octet", "Forth Octet"))
print("%-20s%-20s%-20s%-20s" % (first_octet, second_octet,
third_octet, forth_octet))
|
class Worker():
def __init__(self, isim,maas,departman):
print("çalışan sınıfının init fonksiyonu")
self.isim = isim
self.maas = maas
self.departman = departman
def bilgilerigoster(self):
print("çalışan sınıfının bilgileri")
print("isim : {}\nMaaş : {}\nDepartman: {}\n ".format(self.isim, self.maas, self.departman))
def departman_degistir(self, yeni_departman):
self.departman = yeni_departman |
class Region:
def __init__ (self, bbox, region_):
self.bbox = bbox # [xmin, ymin, xmax, ymax] float
self.region_ = region_ # (d_region)
|
# Copyright 2018 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Proxy file for referencing processor partials."""
load(
"@build_bazel_rules_apple//apple/internal/partials:app_assets_validation.bzl",
_app_assets_validation_partial = "app_assets_validation_partial",
)
load(
"@build_bazel_rules_apple//apple/internal/partials:apple_bundle_info.bzl",
_apple_bundle_info_partial = "apple_bundle_info_partial",
)
load(
"@build_bazel_rules_apple//apple/internal/partials:apple_symbols_file.bzl",
_apple_symbols_file_partial = "apple_symbols_file_partial",
)
load(
"@build_bazel_rules_apple//apple/internal/partials:binary.bzl",
_binary_partial = "binary_partial",
)
load(
"@build_bazel_rules_apple//apple/internal/partials:bitcode_symbols.bzl",
_bitcode_symbols_partial = "bitcode_symbols_partial",
)
load(
"@build_bazel_rules_apple//apple/internal/partials:clang_rt_dylibs.bzl",
_clang_rt_dylibs_partial = "clang_rt_dylibs_partial",
)
load(
"@build_bazel_rules_apple//apple/internal/partials:debug_symbols.bzl",
_debug_symbols_partial = "debug_symbols_partial",
)
load(
"@build_bazel_rules_apple//apple/internal/partials:embedded_bundles.bzl",
_embedded_bundles_partial = "embedded_bundles_partial",
)
load(
"@build_bazel_rules_apple//apple/internal/partials:extension_safe_validation.bzl",
_extension_safe_validation_partial = "extension_safe_validation_partial",
)
load(
"@build_bazel_rules_apple//apple/internal/partials:framework_headers.bzl",
_framework_headers_partial = "framework_headers_partial",
)
load(
"@build_bazel_rules_apple//apple/internal/partials:framework_import.bzl",
_framework_import_partial = "framework_import_partial",
)
load(
"@build_bazel_rules_apple//apple/internal/partials:framework_provider.bzl",
_framework_provider_partial = "framework_provider_partial",
)
load(
"@build_bazel_rules_apple//apple/internal/partials:macos_additional_contents.bzl",
_macos_additional_contents_partial = "macos_additional_contents_partial",
)
load(
"@build_bazel_rules_apple//apple/internal/partials:messages_stub.bzl",
_messages_stub_partial = "messages_stub_partial",
)
load(
"@build_bazel_rules_apple//apple/internal/partials:provisioning_profile.bzl",
_provisioning_profile_partial = "provisioning_profile_partial",
)
load(
"@build_bazel_rules_apple//apple/internal/partials:resources.bzl",
_resources_partial = "resources_partial",
)
load(
"@build_bazel_rules_apple//apple/internal/partials:settings_bundle.bzl",
_settings_bundle_partial = "settings_bundle_partial",
)
load(
"@build_bazel_rules_apple//apple/internal/partials:static_framework_header_modulemap.bzl",
_static_framework_header_modulemap_partial = "static_framework_header_modulemap_partial",
)
load(
"@build_bazel_rules_apple//apple/internal/partials:swift_dylibs.bzl",
_swift_dylibs_partial = "swift_dylibs_partial",
)
load(
"@build_bazel_rules_apple//apple/internal/partials:swift_dynamic_framework.bzl",
_swift_dynamic_framework_partial = "swift_dynamic_framework_partial",
)
load(
"@build_bazel_rules_apple//apple/internal/partials:swift_static_framework.bzl",
_swift_static_framework_partial = "swift_static_framework_partial",
)
load(
"@build_bazel_rules_apple//apple/internal/partials:watchos_stub.bzl",
_watchos_stub_partial = "watchos_stub_partial",
)
partials = struct(
app_assets_validation_partial = _app_assets_validation_partial,
apple_bundle_info_partial = _apple_bundle_info_partial,
binary_partial = _binary_partial,
bitcode_symbols_partial = _bitcode_symbols_partial,
clang_rt_dylibs_partial = _clang_rt_dylibs_partial,
debug_symbols_partial = _debug_symbols_partial,
embedded_bundles_partial = _embedded_bundles_partial,
extension_safe_validation_partial = _extension_safe_validation_partial,
framework_import_partial = _framework_import_partial,
framework_headers_partial = _framework_headers_partial,
framework_provider_partial = _framework_provider_partial,
macos_additional_contents_partial = _macos_additional_contents_partial,
messages_stub_partial = _messages_stub_partial,
provisioning_profile_partial = _provisioning_profile_partial,
resources_partial = _resources_partial,
settings_bundle_partial = _settings_bundle_partial,
static_framework_header_modulemap_partial = _static_framework_header_modulemap_partial,
swift_dylibs_partial = _swift_dylibs_partial,
swift_dynamic_framework_partial = _swift_dynamic_framework_partial,
swift_static_framework_partial = _swift_static_framework_partial,
apple_symbols_file_partial = _apple_symbols_file_partial,
watchos_stub_partial = _watchos_stub_partial,
)
|
def metade(x):
s = x / 2
return s
def dobro(n):
return 2 * n
def aumentar(n, p):
return (n * (p / 100)) + n
|
# Given a non-negative integer num represented as a string, remove k digits from the number so that the new number is the smallest possible.
# Note:
# The length of num is less than 10002 and will be ≥ k.
# The given num does not contain any leading zero.
# Example 1:
# Input: num = "1432219", k = 3
# Output: "1219"
# Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.
# Example 2:
# Input: num = "10200", k = 1
# Output: "200"
# Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes
class Solution(object):
def removeKdigits(self, num, k):
"""
:type num: str
:type k: int
:rtype: str
"""
while k > 0:
k -= 1
i = 0
while i < len(num) - 1:
if num[i] > num[i + 1]:
break
i += 1
num = num[:i] + num[i+1:]
return str(int(num)) if num else "0"
def removeKdigits2(self, num, k):
stack = []
for i in num:
if stack and stack[-1] > i and k:
stack.pop()
k -= 1
stack.append(i)
while stack and k:
k -= 1
stack.pop()
while stack and stack[0] == "0":
stack.pop(0)
return "".join(stack) if stack else "0"
# Time: O(n * k)
# Space: O(n)
# Difficulty: medium |
"""
Bir sayının çift olup olmadığını sorgulayan bir fonksiyon yazın. Bu fonksiyon, eğer sayı çift ise return ile bu değeri dönsün.
Ancak sayı tek sayı ise fonksiyon raise ile ValueError hatası fırlatsın. Daha sonra, içinde çift ve tek sayılar bulunduran bir liste
tanımlayın ve liste üzerinde gezinerek ekrana sadece çift sayıları bastırın.
"""
def ciftMiDegilMi(sayi):
if sayi % 2 == 0:
return sayi
else:
raise ValueError
sayıListesi = range(1,26)
ciftSayilar = list()
for i in sayıListesi:
try:
print(ciftMiDegilMi(i))
ciftSayilar.append(i)
except ValueError:
print("Hata, tek sayı : ",i)
print("Çift Sayılar 1-25 : ",*ciftSayilar)
#Problem Çözüldü. |
# -*- coding: utf-8 -*-
'''
Package containing network handshakes
'''
|
def _merge(a, b):
members = set()
members.update(a.members if isinstance(a, TagSet) else {a})
members.update(b.members if isinstance(b, TagSet) else {b})
return TagSet(members)
class Tag:
def __init__(self, name):
self.name = name
__and__ = _merge
__rand__ = _merge
def __repr__(self):
return f"ptera.tag.{self.name}"
__str__ = __repr__
class TagSet:
def __init__(self, members):
self.members = frozenset(members)
__and__ = _merge
__rand__ = _merge
def __eq__(self, other):
return isinstance(other, TagSet) and other.members == self.members
def __repr__(self):
return " & ".join(sorted(map(str, self.members)))
__str__ = __repr__
class _TagFactory:
def __init__(self):
self._cache = {}
def __getattr__(self, name):
if name not in self._cache:
self._cache[name] = Tag(name)
return self._cache[name]
def match_tag(to_match, tg):
if to_match is None:
return True
if tg is None:
return False
elif isinstance(tg, TagSet):
return any(cat == to_match for cat in tg.members)
else:
return tg == to_match
def get_tags(*tags):
tags = [getattr(tag, tg) if isinstance(tg, str) else tg for tg in tags]
if len(tags) == 1:
return tags[0]
else:
return TagSet(tags)
tag = _TagFactory()
|
'''Unstamp Mail Submission Agent Server
This server receives outgoing mail from the email client, and gives it to the
Mail Transfer Agent to send.
'''
|
#!/usr/bin/python3
sites = ["Baidu", "Google","Runoob","Taobao"]
for site in sites:
if site == "Runoob":
print("菜鸟教程!")
break
print("循环数据 " + site)
else:
print("没有循环数据!")
print("完成循环!") |
# Copyright 2013 Locaweb.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @author: Thiago Morello (morellon), Locaweb.
# @author: Willian Molinari (PotHix), Locaweb.
class Formatter(object):
def host(self, host_id, name, address):
return {
'id': host_id,
'name': name,
'address': address
}
def storage(self, sr_id, name, sr_type, used_space, allocated_space,
physical_size):
return {
'id': sr_id,
'name': name,
'type': sr_type,
'used_space': int(used_space),
'allocated_space': int(allocated_space),
'size': int(physical_size)
}
def guest(self, vmid, name, cpus, mem, hdd, pvirt, tools, ip, state, host):
return {
'id': vmid,
'name': name,
'cpus': int(cpus),
'memory': int(mem),
'hdd': hdd,
'paravirtualized': pvirt,
'tools_up_to_date': tools,
'ip': ip,
'state': state,
'host': host
}
def disk(self, disk_id, name, device, size, extra_info):
return {
'id': disk_id,
'name': name,
'number': device,
'size': size,
'extra_info': extra_info
}
def snapshot(self, snap_id, name, state=None, path=None, created=None):
return {
'id': snap_id,
'name': name,
'state': state,
'path': path,
'created': created
}
def network_interface(self, vif_id, device, mac, name_label, locking_mode, ipv4_allowed, ipv6_allowed, rate_limit=None):
return {
'id': vif_id,
'number': device,
'mac': mac,
'locking_mode': locking_mode,
'ipv4_allowed': ipv4_allowed,
'ipv6_allowed': ipv6_allowed,
'network': name_label,
'rate_limit': rate_limit
}
def pool(self, used_memory, total_memory, uuid, master, software_info=None):
return {
"used_memory": used_memory,
"total_memory": total_memory,
"uuid": uuid,
"master": master,
"software_info": software_info
}
|
class Settings:
def __init__(self):
# Rotors = Moveable wheels
self.rotors = {
"I": {"sequence": "ekmflgdqvzntowyhxuspaibrcj", "notches": ["r"]},
"II": {"sequence": "ajdksiruxblhwtmcqgznpyfvoe", "notches": ["f"]},
"III": {"sequence": "bdfhjlcprtxvznyeiwgakmusqo", "notches": ["w"]},
"IV": {"sequence": "esovpzjayquirhxlnftgkdcmwb", "notches": ["k"]},
"V": {"sequence": "vzbrgityupsdnhlxawmjqofeck", "notches": ["a"]},
"VI": {"sequence": "jpgvoumfyqbenhzrdkasxlictw", "notches": ["a", "n"]},
"VII": {"sequence": "nzjhgrcxmyswboufaivlpekqdt", "notches": ["a", "n"]},
"VIII": {"sequence": "fkqhtlxocbjspdzramewniuygv", "notches": ["a", "n"]},
}
# Reflector = Reflect the letter back for a second round of encryption
self.reflectors = {
"UKW-B-thin": "enkqauywjicopblmdxzvfthrgs",
"UKW-C-thin": "rdobjntkvehmlfcwzaxgyipsuq",
}
# zusatzwalze = left-most WHEEL, does not move
self.zusatzwalze = {
"beta": {"sequence": "leyjvcnixwpbqmdrtakzgfuhos", "notches": []},
"gamma": {"sequence": "fsokanuerhmbtiycwlqpzxvgjd", "notches": []},
}
self.alphabet = "abcdefghijklmnopqrstuvwxyz"
self.config = None
def to_position(self, param):
# convert a configuration parameter (letter or number) to the position it has in the alphabet
if type(param) is str and param in self.alphabet:
# Returns the position in the alphabet of a letter
return self.alphabet.index(param.lower())
elif type(param) is int and param > 0 and param < 27:
# This is already a number, return it - 1
return param - 1
else:
raise Exception("Invalid param. '" + str(param) + "' is not a valid argument")
def configure(self, configObj):
# create the actual configuration object
self.config = {
"reflector": configObj["reflector"],
"plugboard": configObj["plugboard"],
"rotors": {
"zusatzwalze": {
"rotor": configObj["zus"].get("rot"),
"starting_pos": self.to_position(configObj["zus"].get("pos")),
"ringstellung": self.to_position(configObj["zus"].get("ring")),
},
"rotor3": {
"rotor": configObj["rot3"].get("rot"),
"starting_pos": self.to_position(configObj["rot3"].get("pos")),
"ringstellung": self.to_position(configObj["rot3"].get("ring")),
},
"rotor2": {
"rotor": configObj["rot2"].get("rot"),
"starting_pos": self.to_position(configObj["rot2"].get("pos")),
"ringstellung": self.to_position(configObj["rot2"].get("ring")),
},
"rotor1": {
"rotor": configObj["rot1"].get("rot"),
"starting_pos": self.to_position(configObj["rot1"].get("pos")),
"ringstellung": self.to_position(configObj["rot1"].get("ring")),
},
},
}
def get_rotor(self, rotorName):
# return the rotor configuration after taking its name as input
if self.config != None:
if (rotorName in ["rotor1", "rotor2", "rotor3"]):
return {
"rotor": self.rotors[self.config["rotors"][rotorName]["rotor"]],
"starting_pos": self.config["rotors"][rotorName]["starting_pos"],
"ringstellung": self.config["rotors"][rotorName]["ringstellung"]
}
elif (rotorName == "zusatzwalze"):
return {
"rotor": self.zusatzwalze[self.config["rotors"][rotorName]["rotor"]],
"starting_pos": self.config["rotors"][rotorName]["starting_pos"],
"ringstellung": self.config["rotors"][rotorName]["ringstellung"]
}
return None
def get_reflector(self):
if self.config != None and self.config.get("reflector"):
return self.reflectors[self.config["reflector"]]
return None
def plugboard(self):
if self.config != None:
return self.config.get("plugboard", [])
return None |
# Man kan ændre globale variabler i funktioner
# Any variable which is changed or created inside of a function is local, if it hasn’t been declared as a global variable.
# (brug nonlocal for ydre namespace)
a = 1
b = 2
print("a =",a)
print("b =",b)
# Parameter er lokal variabel
def forsøg4( a ):
global b
a = a + 10
b = b + 10
print("inde i funktion: a =",a)
print("inde i funktion: b =",b)
forsøg4(4)
print("a =",a)
print("b =",b)
|
# Copyright 2019 Nicole Borrelli
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
VANILLA_FLAGS = {
"garland_defeated": 0x01,
"bridge_to_be_rebuilt": 0x02,
"obtained_bridge": 0x03,
"obtained_lute": 0x04,
"obtained_ship": 0x05,
"obtained_crown": 0x06,
"obtained_crystal_eye": 0x07,
"obtained_jolt_tonic": 0x08,
"obtained_mystic_key": 0x09,
"obtained_nitro_powder": 0x0a,
"obtained_canal": 0x0b,
"vampire_defeated": 0x0c,
"obtained_ruby": 0x0d,
"titan_fed": 0x0e,
"obtained_earth_rod": 0x0f,
"broke_earth_plate": 0x10,
"lit_earth_crystal": 0x11,
"obtained_canoe": 0x12,
"lit_fire_crystal": 0x13,
"obtained_levistone": 0x14,
"airship_visible": 0x15,
"can_undertake_trials": 0x16,
"obtained_rats_tail": 0x17,
"obtained_promotion": 0x18,
"released_fairy": 0x19,
"obtained_oxyale": 0x1a,
"opened_sea_shrine": 0x1b,
"obtained_rosetta_stone": 0x1c,
"lit_water_crystal": 0x1d,
"learned_lufienian": 0x1e,
"obtained_chime": 0x1f,
"obtained_warp_cube": 0x20,
"obtained_adamantite": 0x21,
"lit_air_crystal": 0x22,
"obtained_excalibur": 0x23,
"black_orb_removed": 0x24,
"broke_lute_plate": 0x25,
"defeated_chaos": 0x26,
"heard_matoyas_plight": 0x27,
"heard_kings_plight": 0x28,
"watched_bridge_credits": 0x29
}
|
#!/usr/bin/env python3
#encoding=utf-8
#-------------------------------------------------
# Usage: python3 4-getattribute_to_compute_attribute.py
# Description: attribute management 4 of 4
# Same, but with generic __getattribute__ all attribute interception
#-------------------------------------------------
class Powers(object): # Need (object) in 2.X only
def __init__(self, square, cube):
self._square = square
self._cube = cube
def __getattribute__(self, name):
if name == 'square':
return object.__getattribute__(self, '_square') ** 2 # call superclass's __getattribute__, avoid recursive loop
elif name == 'cube':
return object.__getattribute__(self, '_cube') ** 3 # call superclass's __getattribute__, avoid recursive loop
else:
return object.__getattribute__(self, name) # call superclass's __getattribute__, avoid recursive loop
def __setattr__(self, name, value):
if name == 'square':
object.__setattr__(self, '_square', value) # Or use __dict__
elif name == 'cube':
object.__setattr__(self, '_cube', value)
else:
object.__setattr__(self, name , value)
if __name__ == '__main__':
X = Powers(3, 4)
print(X.square) # 3 ** 2 = 9
print(X.cube) # 4 ** 3 = 64
X.square = 5
print(X.square) # 5 ** 2 = 25
X.cube = 7
print(X.cube)
|
#!/usr/bin/python3
# files.py by Bill Weinman [http://bw.org/]
# This is an exercise file from Python 3 Essential Training on lynda.com
# Copyright 2010 The BearHeart Group, LLC
def main():
f = open('lines.txt')
for line in f:
print(line, end = '')
if __name__ == "__main__": main()
|
"""Common functions."""
__all__ = ['rshift']
def rshift(integer: int, shift: int) -> int:
"""Logical right binary shift."""
if integer >= 0:
return integer >> shift
return (integer + 0x100000000) >> shift
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.